Allow ip for hostname

I am trying to resolve the hostname from an ip address. I tried using gethostbyaddr()and getnameinfo(), but in many cases the hostname is not resolved at all. Is there a better way to turn the 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";
}
+5
source share
2 answers

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

No, the getnameinfo()method of choice.


You can check the result getnameinfo()on EAI_AGAIN, and by repeating the request.


EAI_OVERFLOW , . , 259 , , , EAI_OVERFLOW...; -)


BTW: excanoe getaddrinfo() getnameinfo()... - gethostbyaddr() gethostbyname() - . (-) .

+5

Windows ( WSADATA, * nix) :)

  #include <stdio.h>
  #include <stdlib.h>
  #include <stdint.h>

  #include <winsock2.h>

  int main(){
    struct addrinfo    hints;
    struct addrinfo   *res=0;
    int       status;

    WSADATA   wsadata;
    int statuswsadata;
    if((statuswsadata=WSAStartup(MAKEWORD(2,2),&wsadata))!=0){
      printf("WSAStartup failed: %d\n",statuswsadata);
    }

    hints.ai_family   =AF_INET;

    status=getaddrinfo("87.250.251.11",0,0,&res);

    {
      char host[512],port[128];

      status=getnameinfo(res->ai_addr,res->ai_addrlen,host,512,0,0,0);

      printf("Host: %s",host);

      freeaddrinfo(res);
    }
  }

:

d:\temp\stack>ip
Host: yandex.ru

87.250.251.11 yandex.ru:

C:\Users\user>ping yandex.ru

Pinging yandex.ru [87.250.251.11] with 32 bytes of data:
Reply from 87.250.251.11: bytes=32 time=21ms TTL=56
Reply from 87.250.251.11: bytes=32 time=21ms TTL=56
Reply from 87.250.251.11: bytes=32 time=21ms TTL=56

Ping statistics for 87.250.251.11:
    Packets: Sent = 3, Received = 3, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
    Minimum = 21ms, Maximum = 21ms, Average = 21ms

, .

+4

All Articles