今天看netfilter的源码,发现一个打印点分十进制的好方法:使用NIPQUAD和NIPQUAD_FMT宏:
#define NIPQUAD_FMT "%u.%u.%u.%u" #define NIPQUAD(addr) \ ((unsigned char *)&addr)[0], \ ((unsigned char *)&addr)[1], \ ((unsigned char *)&addr)[2], \ ((unsigned char *)&addr)[3]
写个测试代码:
#include <stdio.h> #define NIPQUAD_FMT "%u.%u.%u.%u" #define NIPQUAD(addr) \ ((unsigned char *)&addr)[0], \ ((unsigned char *)&addr)[1], \ ((unsigned char *)&addr)[2], \ ((unsigned char *)&addr)[3] int main() { unsigned int ip; ip = htonl(3232235777); printf("ip = " NIPQUAD_FMT "\n", NIPQUAD(ip)); }
输出结果:
tony@ubuntu-a:~/code$ ./a.out
ip = 192.168.1.1
这个用法要注意的就是,NIPQUAD的参数需要是网络序的,所以事先用htonl转一下就可以了。
另外还看到一种用法,就是使用%pI4打印地址:
sprintf(buffer, "%pI4", &ip);
网上是这样说的:
The kernel's family of
printf()
functions has a special format specifier for IP-addresses (%pI4
for IPv4-addresses,%pI6
for IPv6).
也就是说这种格式仅供内核来使用,一般用户程序是不能用的。