admin管理员组文章数量:1356889
What is wrong with this simple piece of C code?
int main(int argc, char **argv) {
struct sockaddr_in servaddr;
char buf[INET_ADDRSTRLEN];
memset(&servaddr, 0, sizeof(servaddr));
servaddr.sin_addr.s_addr = inet_addr("127.0.0.1");
servaddr.sin_port = htons(22000);
servaddr.sin_family = AF_INET;
fprintf(stderr, "addrinfo: %s\n",
inet_ntop(AF_INET, &servaddr, buf, INET_ADDRSTRLEN));
}
The code prints: addrinfo: 2.0.85.240
I would prefer it to print: addrinfo: 127.0.0.1
What is wrong with this simple piece of C code?
int main(int argc, char **argv) {
struct sockaddr_in servaddr;
char buf[INET_ADDRSTRLEN];
memset(&servaddr, 0, sizeof(servaddr));
servaddr.sin_addr.s_addr = inet_addr("127.0.0.1");
servaddr.sin_port = htons(22000);
servaddr.sin_family = AF_INET;
fprintf(stderr, "addrinfo: %s\n",
inet_ntop(AF_INET, &servaddr, buf, INET_ADDRSTRLEN));
}
The code prints: addrinfo: 2.0.85.240
I would prefer it to print: addrinfo: 127.0.0.1
1 Answer
Reset to default 5The problem is that you are passing the address of the entire server structure to the inet_ntop
function. But if you look at the documentation for the inet_ntop function, you will see that paddr
should be "A pointer to the IP address in network byte [order] to convert to a string." So the call should be:
inet_ntop(AF_INET, &servaddr.sin_addr, buf, INET_ADDRSTRLEN));
本文标签: What is wrong with this simple IP example in CStack Overflow
版权声明:本文标题:What is wrong with this simple IP example in C? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1743966190a2569930.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
#include
lines andint main()
. Now it is impossible to try the code (without adding more code, which then may be different from your code). – hyde Commented Mar 31 at 5:54inet_ntop(AF_INET, &servaddr.sin_addr.s_addr, buf, INET_ADDRSTRLEN)
– 4386427 Commented Mar 31 at 6:21