简体   繁体   English

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

[英]inet_ntoa gives the same result when called with two different addresses

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

The output is: 输出是:

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

I know printf parse arg from right to left or vise versa is platform-dependent, but why the output is the same value, please help to explain. 我知道printf parse arg从右到左或反之亦然是平台相关的,但为什么输出是相同的值,请帮忙解释一下。

From the Linux man pages : https://linux.die.net/man/3/inet_ntoa 从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. inet_ntoa()函数将以网络字节顺序给出的Internet主机地址转换为IPv4点分十进制表示法中的字符串。 The string is returned in a statically allocated buffer, which subsequent calls will overwrite. 该字符串在静态分配的缓冲区中返回,后续调用将覆盖该缓冲区。

It seems the two calls the inet_nota() share a buffer, so calling the function twice overwrites whats in the buffer and replaces it with the next call, thus you get the same output 似乎两个调用inet_nota()共享一个缓冲区,因此调用该函数两次会覆盖缓冲区中的什么并将其替换为下一个调用,从而获得相同的输出

inet_ntoa() uses an internal buffer to convert an address to a string. inet_ntoa()使用内部缓冲区将地址转换为字符串。 Every time you call it it rewrites the same buffer with the new address. 每次调用它时,它都会用新地址重写相同的缓冲区。 So both calls to inet_ntoa() are returning the same pointer, and thus printf() prints the same string twice. 因此,对inet_ntoa()两次调用都返回相同的指针,因此printf()打印两次相同的字符串。 inet_ntoa() does this so that you don't have to free() a string every time you call it. inet_ntoa()执行此操作,以便每次调用时都不必free()字符串。 If you want your output to look the way you expect you can do this: 如果您希望输出看起来像您期望的那样,您可以这样做:

 printf("%s <--> ", inet_ntoa(addr1))
 printf("%s\n", inet_ntoa(addr2));

That way printf() will have printed the first address before the second call to inet_ntoa() overwrites it. 这样printf()将在第二次调用inet_ntoa()之前打印第一个地址。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM