-1

I've this code made in c++ to connect to a server but every time I try "gethostbyname" the value is null(or optimized away and not available).

WSADATA wsaData;
if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) {
    cout << "WSAStartup failed.\n";
    system("pause");
    return 1;
}
hostent *host = gethostbyname("www.example.com");

I've tried hostent as volatile but still gives null. Is there any other way to make this work? I've tried too Optimization disabled but keeps giving null.

user207421
  • 305,947
  • 44
  • 307
  • 483
Manueel
  • 13
  • 3
  • 7
  • 1
    "Return value If no error occurs, gethostbyname returns a pointer to the hostent structure described above. Otherwise, it returns a null pointer and a specific error number can be retrieved by calling WSAGetLastError." (MSDN) – lorro Jun 23 '16 at 21:21
  • 1
    What is the assumed relationship between the opened socket and the host query? – Thomas B Preusser Jun 23 '16 at 21:23

1 Answers1

4

host is null on error. Check the return value of WSAGetLastError() to figure out whats wrong.

Try calling ping www.example.com in a cmd shell to check whether the target is reachable from your machine.

To not optimize add:

if(host!=NULL && host->h_name)
    cout << "host: " << host->h_name << std::endl;

Don't store pointers returned by gethostbyname(). They are overridden on the next call by the same thread.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
lexx9999
  • 736
  • 3
  • 9
  • `gethostbyname()` fails if it cannot resolve the hostname to an IP address, such as via DNS. `ping` is not the same thing as `gethosbyname()`. `ping` actually checks if the target is reachable on the network, so even if `gethosbyname()` succeeds, `ping` can still fail if there is no network route to the target. – Remy Lebeau Jun 24 '16 at 00:03
  • @ Remy Lebeau I did not claim that it's the same, but if ping fails, gethostbyname will likely also fail. – lexx9999 Jun 24 '16 at 00:14
  • that depends on how `ping` fails. `ping` may be able to resolve the host name into an IP but still not be able to actually communicate with the host machine. – Remy Lebeau Jun 24 '16 at 00:35