Reputation: 2418
The following is the code snippet I've written for accepting connections from the client. I wanted to print the remote host name. getnameinfo() fails with the error: ai_family not supported. I tried different options over the internet like specifying AF_UNSPEC. Nothing is working for me. I printed the sa_family field and it is 62752. Is this a valid value? What am I doing wrong. Any help appreciated.
socklen_t sin_size;
struct sockaddr client_addr;
int sockfd = accept(serv_sockfd,&client_addr, &sin_size);
if(sockfd == -1)
error("Accept failed");
char remote_host[NI_MAXHOST];
cerr <<"sa_family" << client_addr.sa_family<<endl;
int en;
if ((en = getnameinfo(&client_addr, sin_size, remote_host, sizeof(remote_host),NULL, 0, NI_NAMEREQD))!=0)
cerr << "getnameinfo: " << gai_strerror(en);
else
printf("host=%s\n", remote_host);
Upvotes: 2
Views: 2402
Reputation: 71605
Your bug is earlier. The third argument to accept() is supposed to be:
address_len
Points to a socklen_t structure which on input specifies the length of the supplied sockaddr structure, and on output specifies the length of the stored address.
Also, a struct sockaddr
is too small to hold any actual address.
Try:
struct sockaddr_storage client_addr;
socklen_t sin_size = sizeof(client_addr);
int sockfd = accept(serv_sockfd, (struct sockaddr *)&client_addr, &sin_size);
...and then the rest of your code as written.
Upvotes: 1