inet_ntoa 的奇怪 printf 行为 [英] Weird printf behaviour with inet_ntoa
问题描述
#include <sys/socket.h>
#include <err.h>
#include <stdio.h>
#include <arpa/inet.h>
#include <netinet/in.h>
int main(int argc, char **argv) {
struct sockaddr_in X = {0};
X.sin_family = AF_INET;
X.sin_addr.s_addr = inet_addr("127.0.0.1");
X.sin_port = htons(8080);
struct sockaddr_in Y = {0};
Y.sin_family = AF_INET;
Y.sin_addr.s_addr = inet_addr("212.43.159.20");
Y.sin_port = htons(80);
printf("X:Y %s:%s\n", inet_ntoa(X.sin_addr), inet_ntoa(Y.sin_addr));
printf("X %s\n", inet_ntoa(X.sin_addr));
printf("Y %s\n", inet_ntoa(Y.sin_addr));
return 0;
}
为什么第一个 pritnf 打印相同的 IP 两次而不是给出什么?第二个和第三个好像没问题.似乎发生在 linux gcc/clang 和 freebsd clang 上,这是已知的吗?
Why does first pritnf print same IP twice rather than whats given? Second and third seem to be okay. Seems to happend on linux gcc/clang and freebsd clang, is this is something known?
推荐答案
来自 inet_ntoa
的手册页:
inet_ntoa()
函数将 Internet 主机地址转换为给定的按网络字节顺序转换为标准数字和点的字符串符号.字符串在静态分配的缓冲区中返回,随后的调用将覆盖.
The
inet_ntoa()
function converts the Internet host address in given in network byte order to a string in standard numbers-and-dots notation. The string is returned in a statically allocated buffer, which subsequent calls will overwrite.
由于 inet_ntoa
使用静态缓冲区作为其输出,并且因为您在一次函数调用中两次调用它,所以 printf
会传递相同指针的两个副本.它包含最后一次调用的内容.
Since inet_ntoa
uses a static buffer for its output, and because you call it twice in one function call, printf
gets passed two copies of the same pointer. It contains the contents of whichever call was done last.
您需要将打印拆分为两个单独的调用,就像您在以下几行中所做的那样.
You need to split the printing into two separate calls, like you do in the following lines.
这篇关于inet_ntoa 的奇怪 printf 行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!