0

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;
}
MD XF
  • 7,062
  • 7
  • 34
  • 64
foobar
  • 2,596
  • 1
  • 22
  • 48
  • 1
    Don't forget to call `WSACleanup()` for every successful `WSAStartup()`. It is best to call `WSAStartup()` once at app start, then `WSACleanup()` at app exit. But you can call `WSAStartup()` multiple times during the app's lifetime as long as you keep `WSAStartup()` and `WSACleanup()` balanced. – Remy Lebeau Jul 21 '14 at 18:29
  • 1
    Here is the definition/declaration for the WSAData variable: WSADATA WSAData; – Richard Jessop Jun 26 '19 at 14:09

3 Answers3

2

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.

Cornelius
  • 250
  • 4
  • 15
1

The error message says it all. You need to call WSAStartup before gethostname: http://msdn.microsoft.com/en-gb/library/windows/desktop/ms742213(v=vs.85).aspx

Wojtek Surowka
  • 18,864
  • 4
  • 43
  • 48
0

Read the error message: the application has not called WSAStartup

MSalters
  • 159,923
  • 8
  • 140
  • 320