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";
}
I have tried using
gethostbyaddr()
andgetnameinfo()
[...]. 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With