简体   繁体   English

使用printf和inet_ntoa打印IP地址时出现奇怪的错误

[英]strange error when using printf and inet_ntoa to print ip address

struct in_addr a,b,c,d;
if(inet_aton ("10.0.0.1", &a)!=-1 );
    printf("a:%s\n", inet_ntoa(a));
if(inet_aton ("10.0.0.2", &b)!=-1 )
    printf("b:%s\n", inet_ntoa(b));

It's no problem to print the to IP address: 打印到IP地址没有问题:

a:10.0.0.1
b:10.0.0.2

However I found that: 但是我发现:

inet_aton ("10.0.0.3", &c);
inet_aton ("10.0.0.4", &d);
printf("c:%s %s\n", inet_ntoa(c), inet_ntoa(d));
printf("d:%s\n", inet_ntoa(d));

It prints: 它打印:

c:10.0.0.3 d:10.0.0.3
d:10.0.0.4

The strange things is that it prints the wrong IP of d at this line: 奇怪的是,它在此行打印了错误的d IP:

printf("c:%s %s\n", inet_ntoa(c), inet_ntoa(d));

I don't know why! 我不知道为什么!

The manual for inet_ntoa says: inet_ntoa的手册说:

The string is returned in a statically allocated buffer, which subsequent calls will overwrite. 该字符串在静态分配的缓冲区中返回,后续调用将覆盖该缓冲区。

You have two functions in printf("c:%s %s\\n", inet_ntoa(c), inet_ntoa(d)); printf("c:%s %s\\n", inet_ntoa(c), inet_ntoa(d));有两个函数printf("c:%s %s\\n", inet_ntoa(c), inet_ntoa(d)); that overwrite the same buffer. 覆盖相同的缓冲区。

Try if (inet_ntoa(c) == inet_ntoa(d)) , you may be surprised by the result. 尝试if (inet_ntoa(c) == inet_ntoa(d)) ,您可能会对结果感到惊讶。

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

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