开发者

sin_port returned in getaddrinfo wrong

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" and argv[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_port and the whole sockaddr_in structure is in network byte order. You'll need to convert the port with ntohl to use it as a number, but you would be better off never touching sockaddr structures' internals whatsoever. Instead, use getnameinfo with NI_NUMERICHOST and NI_NUMERICSERV to get the address back into a string-based numeric form, then strtol to 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜