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);
Your bug is earlier. The third argument to accept() is supposed to be:
Also, a
struct sockaddris too small to hold any actual address.Try:
…and then the rest of your code as written.