GISmatters GISmatters - 1 year ago 125
C Question

recvfrom() is returning size of buffer instead of number of bytes read

In prep for my first time coding UDP, I'm trying out some example client and server code copied and lightly modified from here. Everything seems to be working except that the value returned by recvfrom() is always the size of the buffer instead of the number of bytes read (if I change my buffer size and recompile, the reported bytes received changes to match the new buffer size although the bytes sent are the same 10 bytes in every test).

Does anyone see any error(s) in this code that would explain the problem (some error-checking removed here for conciseness)? In case it's relevant, I'm compiling and running in bash in a Terminal window on a Macbook Pro running Yosemite 10.10.5:

#include <stdlib.h>
#include <string.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>

#define BUFLEN 1024
#define PORT 9930

int main(void) {
struct sockaddr_in si_me, si_other;
int s, i, slen=sizeof(si_other);
int nrecv;
char buf[BUFLEN];


memset((char *) &si_me, 0, sizeof(si_me));
si_me.sin_family = AF_INET;
si_me.sin_port = htons(PORT);
si_me.sin_addr.s_addr = htonl(INADDR_ANY);
bind(s, &si_me, sizeof(si_me));

while (1) {
nrecv = recvfrom(s, buf, BUFLEN, 0, &si_other, &slen);
printf("Received packet from %s:%d\n%d bytes rec'd\n\n",
inet_ntoa(si_other.sin_addr), ntohs(si_other.sin_port), nrecv);

Answer Source

recvfrom truncates datagrams to the size of your buffer when the buffer is not large enough.

The fact that recvfrom returns the buffer size implies that your buffer size is not big enough, try increasing it to, say, 65535 bytes - the maximum theoretical UDP datagram size.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download