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.
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.