Search code examples
c++winapiwindowmsdnwsastartup

C++: gethostname() failing


I need to get the system host name for which I am using gethostname function

But its failing with error code 10093 which is

WSANOTINITIALISED 10093

Successful WSAStartup not yet performed. Either the application has not called WSAStartup or WSAStartup failed. The application may be accessing a socket that the current active task does not own (that is, trying to share a socket between tasks), or WSACleanup has been called too many times.

Below is my program code:

#include <Winsock2.h>
#include <ws2tcpip.h>
#include <Windows.h>    
#pragma comment(lib, "Ws2_32.lib")

int main()
{    
   char hostname[1024];
   hostname[1023] = '\0';
   gethostname(hostname, 1023);
   int err = WSAGetLastError();    
}

What might be causing this failure?


EDIT

Adding below code before gethostname function call solved the issue.

if (WSAStartup (MAKEWORD(2,2), &WSAData) != 0) 
{
  MessageBox (NULL, TEXT("WSAStartup failed!"), TEXT("Error"), MB_OK);
  return FALSE;
}

Solution

  • It is written in the link you posted:

    A successful WSAStartup call must occur before using this function.

    Call WSAStartup, check its return code, if all went well, call gethostname.