-1

I have a UDP server implementation , Where i am getting Segmentation fault on recvfrom call.

#define SIZEOF      sizeof
#define PKTSIZE    65535

char tmp_buf[PKTSIZE];
struct sockaddr_storage tmp_from;
int tmp_fromlen = 0;
int tmp_bytes;
tmp_bytes = truncate_size_t_to_int(recvfrom(fd, tmp_buf,
                      SIZEOF(tmp_buf), 0,
                      (struct sockaddr *) &tmp_from,
                      (socklen_t *) &tmp_fromlen));

Both bind and connect was successful before this.It's a single thread process. What is wrong with this recvfrom call. Do I need to do SIGALRM signal handling for recvfrom? truncate_size_t_to_int is for size_t to int.

agnel
  • 631
  • 1
  • 7
  • 9
  • 1
    What is `tmp_buf`? What does `SIZEOF` do? – Some programmer dude Oct 28 '15 at 07:02
  • char tmp_buf[PKTSIZE]; #define SIZEOF sizeof – agnel Oct 28 '15 at 07:04
  • This is not enough code! Paste more! Whjat is `PKTSIZE` defined? where is the `fd` opened? – Nidhoegger Oct 28 '15 at 07:05
  • Oh, and you *do* initialize `tmp_fromlen` correctly? And when you run in a debugger, it stops at the `recvfrom` call? What does `truncate_size_t_to_int` do? Please try to create a [Minimal, Complete, and Verifiable Example](http://stackoverflow.com/help/mcve) and show us. – Some programmer dude Oct 28 '15 at 07:07
  • 2
    I think you need to read [the `recvfrom` manual page](http://man7.org/linux/man-pages/man2/recvfrom.2.html), where it says that the socket address length argument needs to be initialized to the length of the corresponding address structure. If you're not interested about the source address pass these arguments as `NULL`. – Some programmer dude Oct 28 '15 at 07:19
  • define tmp_fromlen as _socklen_t tmp_fromlen_ and remove the cast to it in the last argument. that might help. also, initializer on it may need to be sizeof(tmp_from). Thirdly, don't cast the return from recvfrom immediately. Check it for -1 [error], etc. – Craig Estey Oct 28 '15 at 07:20
  • 2
    Finally a hint about style: If you want your code to be maintainable or readable by others (and with "others" I also include *you* a few months down the line), don't redefine common keywords using macros. `sizeof` is `sizeof`, there is simply no need to do anything else that would warrant a macro for it, or any other keyword or standard construct. Also, remember that `recvfrom` returns a `ssize_t` type, and will return the value `-1` on error, do your `truncate_size_t_to_int` handle that case properly? – Some programmer dude Oct 28 '15 at 07:27
  • If you use `connect`, why use `recvfrom`? – David Schwartz Oct 28 '15 at 07:49

1 Answers1

0

recvfrom() can return -1. You can't write correct networking code without storing the result of recv()/recvfrom()/recvmsg() into a variable, testing it for -1, testing it for zero in the case of TCP, and only if it is positive can you proceed to execute code that assumes it.

user207421
  • 305,947
  • 44
  • 307
  • 483