Resolve NoIP hostname to IP Address in C++

411 views Asked by At

I am trying to resolve a NoIP hostname to an IP address so I can connect to it. Below is the code I am currently using, however e->h_name just returns the hostname string I provided to it, so it does not work. In Python, the gethostbyname function does it successfully so I am confused why it wouldn't work in C++.

void ResolveServerDNS(char* hostname) {
    WSADATA wsa;
    WSAStartup(MAKEWORD(2, 2), &wsa);

    hostent* e = gethostbyname(hostname);

    std::cout << e->h_name << '\n';
}
1

There are 1 answers

2
long.kl On

To get the IP address, you need to use this instead:

printf("%s\n", inet_ntoa(*(struct in_addr *)host->h_addr_list[0]));

This is the hostent struct from https://learn.microsoft.com/en-us/windows/win32/api/winsock/ns-winsock-hostent

typedef struct hostent {
  char  *h_name;
  char  **h_aliases;
  short h_addrtype;
  short h_length;
  char  **h_addr_list;
} HOSTENT, *PHOSTENT, *LPHOSTENT;

In your function, it should be:

hostent *e = gethostbyname(hostname); 
std::cout << inet_ntoa(*(struct in_addr *)e->h_addr_list[0]) << '\n';

Let's test with this code : https://godbolt.org/z/zbTx7x3M7

Note: above is an example in case of gethostbyname() returning ok -> you need to take care if host is NULL & maybe DNS returns more IPs for one domain -> let's use a for loop to get all the IPs:

hostent *e = gethostbyname(hostname); 
for (int i = 0; e->h_addr_list[i] != NULL; i++) {
    std::cout << inet_ntoa(*(struct in_addr *)e->h_addr_list[i]) << '\n';
}