c - 当使用两个不同的地址调用时,inet_ntoa 给出相同的结果

标签 c printf

//
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/

相关文章:

c - printf %e 科学记数法在 C 中给出错误的值

c++ - PRNG库支持存储/恢复排序状态?

c - 如何使用 pthread 库在堆上的特定位置创建锁?

c++ - sprintf 等显示函数如何将数字转换为字符串?

C write() 函数没有按预期工作

r - 在 R 中跳过 sprintf 格式字符串中的参数

c - 我得到了 3 个结构,我必须使用堆并将一些数据输入到结构的成员中

c - fprintf 有问题

c - Visual Studio 编译单独的文件

c - 为什么 GCC 在将 void * 传递给 void** 参数时不会给出错误?