inet_ntoa 在使用两个不同地址调用时给出相同的结果 [英] inet_ntoa gives the same result when called with two different addresses

查看:50
本文介绍了inet_ntoa 在使用两个不同地址调用时给出相同的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

//
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从右到左解析arg,反之亦然是平台相关的,但是为什么输出是相同的值,请帮忙解释一下.

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.

推荐答案

来自 Linux 手册页:https://linux.die.net/man/3/inet_ntoa

From the Linux man pages : https://linux.die.net/man/3/inet_ntoa

inet_ntoa() 函数将 Internet 主机地址转换为给定的以网络字节顺序,转换为 IPv4 点分十进制表示法的字符串.该字符串在静态分配的缓冲区中返回,该缓冲区后续调用将覆盖.

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() 的两次调用共享一个缓冲区,因此调用该函数两次会覆盖缓冲区中的内容并将其替换为下一次调用,因此您得到相同的输出

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_ntoa 在使用两个不同地址调用时给出相同的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆