I am trying to implement a simple client that connects to a give address. You’ll notice that I’m printing the given address and the IP address and port after I put it in my sockaddr_in struct.
I get two different addresses even though it should be the same.
Here’s my code:
int createConnection(char * address, char * port) {
cout << address << " " << port << endl;
struct sockaddr_in server;
server.sin_family = AF_INET;
server.sin_port = htons(atoi(port));
inet_aton(address,&(server.sin_addr));
memset(&(server.sin_zero), '\0', 8);
if ((sockFd = socket(PF_INET,SOCK_STREAM,0)) == -1) {
perror("client: socket");
}
if (connect(sockFd,(const sockaddr *)&server,sizeof(struct sockaddr_in)) == -1) {
close(sockFd);
perror("client: connect");
}
char s[INET_ADDRSTRLEN];
inet_ntop(AF_INET, (struct sockaddr *)&server, s, sizeof s);
printf("client: connecting to %s, %i\n", s, server.sin_port);
printf("connected");
return 0;
}
And the output is
132.65.151.39 3000
client: connecting to 2.0.11.184, 47115
My questions:
- Why do I see two different addresses?
- How come the connection does not fail?
What happens is that my program is blocked in recv() later on, so I think it didn’t connect to where I wanted it. Thanks!
It looks like you’re passing the wrong thing to
inet_ntop():You should probably be passing
.sin_addr:For the port, it prints wrong because you need to call
ntohs()to convert back to host byte order:The connection works, presumably because the address is set correctly, in actuality.