0

I have this code:

#include <cstdio>

#ifdef _WIN32
#include <winsock2.h>
#else
#include <sys/socket.h>
#endif


int main() {
  int sock = socket(AF_INET, SOCK_DGRAM,0);
  printf("%d\n",sock);
}

It works good on linux, socket returns 4.

But it does not work on windows when compiled with mingw g++ main.cc -lws2_32. It returns -1. Why is this happening?

T0maas
  • 422
  • 2
  • 12
  • 1
    [`WSAGetLastError`](https://learn.microsoft.com/en-us/windows/win32/api/winsock/nf-winsock-wsagetlasterror) can be helpful in figuring out the something when something goes wrong. – user4581301 Dec 23 '21 at 15:48
  • I forget to add WSAStartup. I didnt know that I need this, I thought that mingw solves this problem internally. – T0maas Dec 24 '21 at 17:43
  • Why is this question marked as duplicate? I did not ask about WSAStartup. I didn't even know that WSAStartup exists. – T0maas Dec 24 '21 at 17:48
  • 1
    Sometimes the answer to a question is to do something you didn't know you needed to do. MinGW doesn't turn on the networking by default because it would be a huge waste for all of the programs that don't use windows sockets. – user4581301 Dec 24 '21 at 19:55
  • 1
    In Linux, the infrastructure provided by the OS is very different and the networking is built in a little better because it was designed in from the start. Micriosoft's Operating systems didn't have networking at all for years. Then winsock showed up and you had to turn it on in order to use it. – user4581301 Dec 24 '21 at 20:06

0 Answers0