简体   繁体   中英

How to receive multiple UDP packets in C?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM