views:

251

answers:

1

I made a function to send an UDP packet to a server and to get the returned packets. When i make a single recvfrom call it works, but i need to get all potential packets from the server within the defined timeout.

Here's my code: http://pastebin.be/23548

Can someone help me? Thanks.

+1  A: 

The SO_RCVTIMEO option that you've set on the socket is effectively an inactivity timer. In other words, by setting RCVTIMEO you're ensuring that the recvfrom call will return after the timer expires even if no data has been received. It doesn't sound like that's exactly what you're trying to do.

There are several ways to do what you're asking... here are a couple of ideas.

If you are comfortable with signals, you could use 'setitimer' to track your maximum timeout. http://linux.die.net/man/2/setitimer

It would send your process a SIGALRM upon timer expiry, and in your signal handler you could set a flag that tells your recvfrom loop to exit.

You could alternatively grab the system time at your starting point and then poll it in your recvfrom loop to see if you've passed the desired timeout value. http://dell5.ma.utexas.edu/cgi-bin/man-cgi?gettimeofday+2

sckor
Thanks for answering? I have still a question before continuing...I removed the fcntl() function and now it works again, as there is also a timeout. But now every response takes 500 ms, which wasn't the case when calling recvfrom once.Why does it behave like that? Shoulnd't it stop the loop as soon as there's no data got from recvfrom?It looks that now it only returns when the timeout reaches...
The recvfrom is a blocking call. So if there are no packets and you haven't set SO_RCVTIMEO (or O_NONBLOCK) it will block forever. I assume you took the signal route, which would cause the recvfrom call to get interrupted upon timer expiry.
sckor