I am writing a server-client program and in the server I use getaddrinfo and getsockname on the server to get info about the local IP addr and locally bound port number .
Using this info, I start my client program and use the getaddrinfo and then just print out the returned values in the servinfo data structure:
getaddrinfo(argc[1], argc[2], &hints, &servinfo); >> server hostname and server port number are passed via command line.
But I notice that the sin_port in servinfo is not the port I am passing via the command line.
1) Does this getaddrinfo return the port number being used by the client as the source port number ?
2) My connect call after the getaddrinfo and socket calls in failing. I do not know why. How do I debug it ?
My client code snippet:
memset(&hints, 0 ,sizeof hints);
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_CANONNAME | AI_NUMERICSERV;
getaddrinfo(argc[1], argc[2], &hints, &servinfo);
for (p = servinfo till p!=NULL)
sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)
connect(sockfd, p->ai_addr, p->ai_addrlen) >>>>> Connect not going through.
I start my client program like this:
./a.out myservername 18844
Thanks !
New answer: You are invoking your program with only one argument, so
argv[1]contains"18844"andargv[2]is a null pointer. This is going to try to connect to a host with numeric IP 18844 and an unspecified port number (which will end up being 0 and failing).Old answer: (relevant but not your problem)
sin_portand the wholesockaddr_instructure is in network byte order. You’ll need to convert the port withntohlto use it as a number, but you would be better off never touchingsockaddrstructures’ internals whatsoever. Instead, usegetnameinfowithNI_NUMERICHOSTandNI_NUMERICSERVto get the address back into a string-based numeric form, thenstrtolto read the port (“service”) number into an integer. This works even for non-IPv4 network address/protocol families (like IPv6) and requires no additional code for supporting new ones.