今天看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).
也就是說這種格式僅供內核來使用,一般用戶程序是不能用的。