//
char ip1[] = "127.0.0.1";
char ip2[] = "211.100.21.179";
printf("ip1: %s\nip2: %s\n", ip1, ip2);
//
long l1 = inet_addr(ip1);
long l2 = inet_addr(ip2);
printf("ip1: %ld\nip2: %ld\n", l1, l2);
//
struct in_addr addr1, addr2;
memcpy(&addr1, &l1, 4);
memcpy(&addr2, &l2, 4);
printf("%u\n", addr1.s_addr);
printf("%u\n", addr2.s_addr);
//
printf("%s\n", inet_ntoa(addr1));
printf("%s\n", inet_ntoa(addr2));
//
printf("%u,%s\n", addr1.s_addr, inet_ntoa(addr1));
printf("%u,%s\n", addr2.s_addr, inet_ntoa(addr2));
printf("%s <--> %s\n", inet_ntoa(addr1), inet_ntoa(addr2));
输出是:
ip1: 127.0.0.1
ip2: 211.100.21.179
ip1: 16777343
ip2: 3004523731
16777343
3004523731
127.0.0.1
211.100.21.179
16777343,127.0.0.1
3004523731,211.100.21.179
211.100.21.179 <--> 211.100.21.179 // why the same??
我知道printf
parse arg 从右到左或反之是平台相关的,但为什么输出的是相同的值,请帮忙解释。
最佳答案
来自 Linux 手册页:https://linux.die.net/man/3/inet_ntoa
The inet_ntoa() function converts the Internet host address in, given in network byte order, to a string in IPv4 dotted-decimal notation. The string is returned in a statically allocated buffer, which subsequent calls will overwrite.
似乎两次调用 inet_nota()
共享一个缓冲区,因此两次调用该函数会覆盖缓冲区中的内容并用下一次调用替换它,因此您得到相同的输出
关于c - 当使用两个不同的地址调用时,inet_ntoa 给出相同的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48799606/