Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resolve ip to hostname

Tags:

c++

c

sockets

I'm trying to resolve a hostname from an ip address. I have tried using gethostbyaddr() and getnameinfo() but in many cases the hostname is not resolved at all. Is there a better way to turn an ip address into a valid hostname?

char* ip = argv[1];
// using gethostbyaddr()
hostent * phe = gethostbyaddr(ip, strlen(ip), AF_INET);
if(phe) {
  cout << phe->h_name << "\n";
}

// using getnameinfo()
char hostname[260];
char service[260];
sockaddr_in address;
memset(&address, 0, sizeof(address));
address.sin_family = AF_INET;
address.sin_addr.s_addr = inet_addr(ip);
int response = getnameinfo((sockaddr*)&address, 
                            sizeof(address), 
                            hostname, 
                            260, 
                            service, 
                            260, 
                            0);
if(response == 0) {
  cout << hostname << "\n";
}
like image 314
Cyclonecode Avatar asked May 12 '12 14:05

Cyclonecode


1 Answers

I have tried using gethostbyaddr() and getnameinfo() [...]. Is there a better way to turn an ip address into a valid hostname?

No, getnameinfo() is the method of choice.


You might check the result of getnameinfo() against EAI_AGAIN, and if equal retry the request.


Also receiving EAI_OVERFLOW does not mean you got no response. Anyhow as you provide 259 characters to place the result in you will mostly likely not get an EAI_OVERFLOW... ;-)


BTW: excanoe is right with his comment on sticking with getaddrinfo() and getnameinfo() ... - gethostbyaddr() and gethostbyname() are somehow deprecated. Also handling their result(s) is complicated and tends to provoke programming errors.

like image 63
alk Avatar answered Oct 05 '22 19:10

alk