P. G.
P. G.

Reputation: 107

Receive UDP message, but go of if there is none

I have a little problem, but haven't found a solution for it.

The problem seems to be quite simple:

I have a process. Within this process I want to check if there is a UDP message sent to the port I'm using. The whole send and receive thing is no problem, if there is a message sent. If there is no message sent, the process is waiting for a message and the program doesn't proceed until the next message is sent.

The question is how can I modify my code to let the process go on if there is no message.

My Code (standard code for receiving UDP messages):

if((nbrecv = recvfrom(s, buffer, BUFFER_SIZE, 0, &remote, &len_remote)) == -1){
    fprintf(stderr, "failure!\n");
    exit(-1);
}

etc.

Upvotes: 0

Views: 220

Answers (1)

Hasturkun
Hasturkun

Reputation: 36412

Your options are as following:

  1. Use select(), poll(), epoll(), etc. to wait for data instead of calling recvfrom() directly
  2. Set your socket to be non-blocking by setting the O_NONBLOCK flag on the socket using fcntl(). This will make recvfrom() return immediately instead of blocking.
  3. (not recommended) Set a receive timeout using the SO_RCVTIMEO socket option.

Upvotes: 2

Related Questions