winsock bind fails (WSAENOTSOCK)

Jul 22, 2014 at 9:16am
Hey guys,

i have a problem with winsock udp sockets.

This the part of the code that fails.
1
2
3
4
5
6
7
8
if (userSocket == INVALID_SOCKET) {
        std::cout << "socket invalid\n";
}
errorNumber = bind(userSocket, (sockaddr*)&userPort, sizeof(userPort));
	if (errorNumber != 0) {
		std::cout << "bind failed: " << WSAGetLastError() << " port: " << portNumber << "\n";
		return false;
	}
The socket is valid but bind fails with WSAENOTSOCK. I'm really out of ideas here. How is that even possible ?
Jul 22, 2014 at 9:39am
You'll need to show the declaration and initialisation of userPort.

While you're at it, please show the initialisation of userSocket.
Last edited on Jul 22, 2014 at 9:40am
Jul 22, 2014 at 9:49am
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
WSADATA wsaData;
SOCKET userSocket;
sockaddr_in userPort;
int errorNumber;

errorNumber = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (errorNumber != 0) {
	std::cout << "init failed\n";
}

userSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (userSocket == INVALID_SOCKET) {
	std::cout << "socket invalid\n";
}

userPort.sin_family = AF_INET;
userPort.sin_addr.s_addr = INADDR_ANY;
userPort.sin_port = htons(portNumber);

errorNumber = bind(userSocket, (struct sockaddr*)&userPort, sizeof(userPort));
if (errorNumber != 0) {
	std::cout << "bind failed: " << WSAGetLastError() << " port: " << portNumber << "\n";
}


As i said the "userSocket == INVALID_SOCKET" does return false. I really do not understand how bind returns WSAENOTSOCK
Jul 22, 2014 at 10:21am
There doesn't appear to be anything wrong with it so I ran it (on W7). There was no error, it seemed ok there too.
Jul 22, 2014 at 10:56am
This is ridiculous. This code fails always with WSAENOTSOCK at bind on my computer. Running on Windows 8 should not be a problem right ?
Jul 22, 2014 at 12:06pm
It is rediculous, and you're right, it should run.

Perhaps it's something external like port restrictions imposed by some firewall or something. Or maybe the port number is too low for a non-admin account. Just guessing ...
Jul 22, 2014 at 3:23pm
I suspect that it has something to do with the typecast of userPort. Narrowing conversions are a PITA, and an explicit cast is not a work around that you should use regularly. You should avoid them where ever you can.

Is there a reason that userPort HAS to be a 'sockaddr_in' instead of the smaller 'sockaddr? If it was a sockaddr from the beginning then casting the other way around is pretty much trouble free.
Jul 22, 2014 at 3:56pm
It is working now. I have no idea why. There was a Windows Update running in the background and the antivirus also. Probably one of theese blocked the outgoing connection.

Thanks for all the suggestions
Topic archived. No new replies allowed.