0

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];

  s=socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);

  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);
  }
}
GISmatters
  • 431
  • 8
  • 20

1 Answers1

1

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.

Maxim Egorushkin
  • 131,725
  • 17
  • 180
  • 271
  • Ah! I neglected to examine the client code carefully b/c my goal was really just to have a simple working server to field data coming from an android device I'm working on. The client example I used sends its whole buffer, not just the short message string as I incorrectly assumed. This wrong assumption and the fact that I only tested server buffer sizes equal to or smaller than the client's buffer led me to the wrong conclusion about where the problem lay... as is most often the case, the problem was in-between my ears! ;) Thanks for your help! – GISmatters Aug 18 '16 at 17:50