4
votes

I've worked with TCP sockets before in Python. It looks pretty similar in C but I can't get anything to work. socket(AF_INET, SOCK_STREAM, 0); returns -1, which of course indicates an error. How could I go so wrong so fast? If you could help me with this problem, that would be nice, but it would be incredibly helpful if you could provide me with some simple, bare bones source code. It doesn't need to even do anything really, and it doesn't need to handle errors. I just need to see how to properly create a server socket, bind it, listen on it, and accept clients and how to create and connect a client socket. I can figure out all the bells and whistles on my own.

Thanks!

4
what does WSAGetLastError() return after your socket call?greatwolf
Does the user the program runs as have permission to use the network?cHao
WSAGetLastError returns 10093, and I routinely run programs written in Python that use sockets.Void Star

4 Answers

9
votes

Have you called WSAStartup before making any other winsock calls?

8
votes

You need to initialise WinSock with the WSAStartup function before you can use sockets. Python's implementation of sockets on Windows likely calls this automatically so you don't need to worry about it, however when using WinSock directly it is important to call WSAStartup before any other WinSock calls, and when your program is done with sockets, you need to call WSACleanup.

WSAData data;

if (WSAStartup(MAKEWORD(2, 2), &data) != 0)
{
    // unable to initialise WinSock, time to quit
}

// WinSock has been successfully initialised, time to make sockets!
int s = socket(...);

// After all WinSock stuff is done, balance out your WSAStartup with a cleanup:
WSACleanup();
0
votes

Probably it's just that the process has no permission to create sockets (errno == EACCES).

Perhaps your python interpreter is getting a different security context, check that.

Anyway, better safe than sorry, so put there something like:

sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock == -1) {
        perror("myapp");
        exit(1);
}

IDK if Winsock actually sets errno, but it should...