简体   繁体   English

如何在C中接收多个UDP数据包?

[英]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. 我做了一个函数,将UDP数据包发送到服务器并获取返回的数据包。 When i make a single recvfrom call it works, but i need to get all potential packets from the server within the defined timeout. 当我进行单个recvfrom调用时,它可以工作,但是我需要在定义的超时时间内从服务器获取所有潜在的数据包。

Here's my code: http://pastebin.be/23548 这是我的代码: 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. 您在套接字上设置的SO_RCVTIMEO选项实际上是一个不活动计时器。 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. 换句话说,通过设置RCVTIMEO,可以确保即使没有收到数据,在计时器到期后recvfrom调用也将返回。 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. 如果您对信号感到满意,则可以使用“ setitimer”来跟踪最大超时。 http://linux.die.net/man/2/setitimer 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. 它将在计时器到期时向您的进程发送SIGALRM,并且您可以在信号处理程序中设置一个标志,告诉您的recvfrom循环退出。

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. 您也可以在起点处获取系统时间,然后在recvfrom循环中对其进行轮询,以查看是否已通过所需的超时值。 http://dell5.ma.utexas.edu/cgi-bin/man-cgi?gettimeofday+2 http://dell5.ma.utexas.edu/cgi-bin/man-cgi?gettimeofday+2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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