0

I am trying to make a client/server homework. I use Visual Studio 2017 and already changed the project settings that i can use sockets (Windows Socket Programming in C) but now my console always says "ERROR while creating Socket ... : No error"

This is my current code:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <WinSock.h>

void PrintErrorExit(char *msg)
{
    perror(msg);
    exit(0);
}

int main()
{
    int randomNumber;
    int sock = 0;
    // Erzeuge das Socket - Verbindung über TCP/IP
    sock = socket(AF_INET, SOCK_STREAM, 0);
    if (sock < 0)
        PrintErrorExit("ERROR while creating Socket ... "); 


}
BlindRob
  • 23
  • 7

1 Answers1

2

Three problems:

  • First, you need to call WSAStartup() to initialize Winsock before you can then use socket().

  • Second, you need to compare the return value of socket() to INVALID_SOCKET, as the documentation says.

  • Third, perror() does not work with Winsock errors, as your example demonstrates. perror() looks at errno, which Winsock does not set. Use WSAGetLastError() instead to get the error code of a failed Winsock function, and then you can print it out as needed.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
David Schwartz
  • 179,497
  • 17
  • 214
  • 278
  • Third, you need to get a Winsock error code using WSAGetLastError(). Converting Winsock errors to strings is slightly tricky. – user253751 Jun 18 '19 at 00:11
  • @immibis "*Converting Winsock errors to strings is slightly tricky*" - not really, you can use [`FormatMessage()`](https://learn.microsoft.com/en-us/windows/desktop/api/winbase/nf-winbase-formatmessage) for that, see [How do I retrieve an error string from WSAGetLastError()?](https://stackoverflow.com/questions/3400922/) – Remy Lebeau Jun 18 '19 at 21:36