Search code examples
c++socketswinsockaccess-violation

Access Violationg when retrieving h_addr_list[0] C++


I am trying to send a GET request and when I try to retrieve h_addr_list[0], I get an access violation error trying to read at location 0x0000000C.

hostent* FAR hostname = gethostbyname(sDetails.host);
serveraddr.sin_addr.s_addr = *(LPDWORD)hostname->h_addr_list[0];

sDetails.host is set to http://www.google.ca for testing.


Solution

  • From the Winsock gethostbyname documentation:

    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.

    The documentation goes on to describe the expected error codes, and it includes example code for calling gethostbyname followed by WSAGetLastError.