整数转ip地址的实现

来源:互联网 发布:怎么清理mac上的其他 编辑:程序博客网 时间:2024/06/05 21:52
  1. #include <sys/cdefs.h>
  2.    31 __FBSDID("$FreeBSD$");
  3.    32
  4.    33 #include <sys/param.h>
  5.    34 #include <sys/systm.h>
  6.    35
  7.    36 #include <netinet/in.h>
  8.    37
  9.    38 char *
  10.    39 inet_ntoa(struct in_addr ina)
  11.    40 {
  12.    41         static char buf[4*sizeof "123"];
  13.    42         unsigned char *ucp = (unsigned char *)&ina;
  14.    43
  15.    44         sprintf(buf, "%d.%d.%d.%d",
  16.    45                 ucp[0] & 0xff,
  17.    46                 ucp[1] & 0xff,
  18.    47                 ucp[2] & 0xff,
  19.    48                 ucp[3] & 0xff);
  20.    49         return buf;
  21.    50 }
  22.    51
  23.    52 char *
  24.    53 inet_ntoa_r(struct in_addr ina, char *buf)
  25.    54 {
  26.    55         unsigned char *ucp = (unsigned char *)&ina;
  27.    56
  28.    57         sprintf(buf, "%d.%d.%d.%d",
  29.    58                 ucp[0] & 0xff,
  30.    59                 ucp[1] & 0xff,
  31.    60                 ucp[2] & 0xff,
  32.    61                 ucp[3] & 0xff);
  33.    62         return buf;
  34.    63 }
复制代码
另外一个
http://fxr.watson.org/fxr/source/libkern/inet_ntoa.c?v=DFBSD
多了个kprintf,还是直接用上面的sprintf的吧。
  1. #include <sys/param.h>
  2.    35 #include <sys/systm.h>
  3.    36
  4.    37 #include <netinet/in.h>
  5.    38
  6.    39 char *
  7.    40 inet_ntoa(struct in_addr ina)
  8.    41 {
  9.    42         static char buf[sizeof "aaa.bbb.ccc.ddd"];
  10.    43         unsigned char *ucp = (unsigned char *)&ina;
  11.    44
  12.    45         ksprintf(buf, "%d.%d.%d.%d",
  13.    46                  ucp[0] & 0xff,
  14.    47                  ucp[1] & 0xff,
  15.    48                  ucp[2] & 0xff,
  16.    49                  ucp[3] & 0xff);
  17.    50         return buf;
  18.    51 }

0 0
原创粉丝点击