Chili
Chili

Reputation: 5

UDP recv fails when receiving more than 8 bytes

I want to receive data via c++ non-blocking recv and everything works as expected for up to 8 bytes payload but when I try to receive 9 bytes or more, recv returns -1 while errno is 0.

Here are the relevant parts of my code. Return values of init-fcns are checked and ok, just left that out to shorten the snippet.

Init Code:

WSADATA w;
HANDLE soc, sem;
SOCKADDR_IN addr;

err = WSAStartup(0x0202, &w);
soc = socket(AF_INET, SOCK_DGRAM, 0);
memset((void *)&addr, '\0', sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(50001);
addr.sin_addr.s_addr = ADDR_ANY;

sem = CreateEvent(nullptr, false, false, nullptr);
WSAEventSelect(soc, sem, FD_READ);

Receiver thread:

char buf[10000];
int bytes_read = 0;

while (true){
    WSAWaitForMultipleEvents(1, enqueue_sem, false, WSA_INFINITE, false);

    bytes_read = recv(soc, buf, sizeof(buf), 0);
    cout << bytes_read << ":" << strerror(errno) << endl;
    cout << buf << endl;
}

When I'm sending 9 bytes or more, the packet is ok (checked via whireshark) and even the first 8 bytes are written to buf, but all following bytes are lost.

Thank you in advance

Upvotes: 0

Views: 667

Answers (1)

Steffen Ullrich
Steffen Ullrich

Reputation: 123491

My wild guess is that your code looks slightly different to what you show us:

 char global_buf[10000];
 char *buf = global_buf;
 recv(soc,buf,sizeof(buf),0);

In this case sizeof(buf) would not be 10000 but instead 8 (size of pointer on 64bit platforms), which would explain why you only can receive 8 bytes.

Upvotes: 2

Related Questions