Nothing received from recvfrom on windows

4.1k views Asked by At

I have some problems on Windows 8 using recvfrom. I have a socket which is bound to INADDR_ANY (0.0.0.0), and i'd like to receive some packets on it.

The problem is that I see those packets in Wireshark, but recvfrom never tells me that the received size is greater than 0. I've tried biding the socket to 127.0.0.1 or even to my local IPv4 address, I never get anything. The port used is 7321 (locally)

I use the ENet library for the creation of the socket, and then I used that socket in recvfrom. Here's the code that never returns the expected packets.

uint8_t* buffer; // max size needed normally (only used for stun)
buffer = (uint8_t*)(malloc(sizeof(uint8_t)*2048));
memset(buffer, 0, 2048);

socklen_t from_len;
struct sockaddr addr;

from_len = sizeof(addr);
int len = recvfrom(m_host->socket, (char*)buffer, 2048, 0, &addr, &from_len); //m_host is of type ENetHost, the socket in it is a file descriptor like standard sockets

As I said, it's a bit weird as Wireshark shows me the packets (which are STUN responses if you want to know).

Can someone help me find out what is missing that may be causing this issue?

2

There are 2 answers

10
Remy Lebeau On BEST ANSWER

Your addr variable is declared as a sockaddr. It needs to be declared as a sockaddr_in (works with IPv4 only) or SOCKADDR_STORAGE (works with both IPv4 and IPv6), and then typecast it to sockaddr* when passing it to recvfrom().

Aside from that, you say that recvfrom() is not returning >= 0. So what is it actually returning? If it returns 0, then a 0-length packet was received (impossible for TCP, but possible for UDP). If it returns -1 (aka SOCKET_ERROR), then an error occured so use WSAGetLastError() to find out what that error actually is.

1
Todd Withers On

I can think of 2 possible reasons you are having the problem:

1) You might not have the port correct on your sendto & recvfrom socket. So say you are sending packets to port 6000, but your recvfrom is listening on port 6001 or something. Just double check both programs are using the same port.

2) Windows firewall. I would run the program as an admin just to be safe, but also make sure you allow your program through windows firewall to communicate using private or public networks.