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