如何在C中接收多个UDP数据包?
我编写了一个函数来将 UDP 数据包发送到服务器并获取返回的数据包。 当我进行单个 recvfrom 调用时,它可以工作,但我需要在定义的超时内从服务器获取所有潜在的数据包。
这是我的代码: http://pastebin.be/23548
有人可以帮助我吗? 谢谢。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您在套接字上设置的 SO_RCVTIMEO 选项实际上是一个不活动计时器。换句话说,通过设置 RCVTIMEO,您可以确保即使没有收到数据,recvfrom 调用也会在计时器到期后返回。听起来这并不正是您想要做的。
有几种方法可以满足您的要求......这里有一些想法。
如果您对信号感到满意,您可以使用“setitimer”来跟踪最大超时。
http://linux.die.net/man/2/setitimer
它会发送您在计时器到期时处理 SIGALRM,并且在信号处理程序中您可以设置一个标志来告诉您的 recvfrom 循环退出。
您也可以在起始点获取系统时间,然后在 recvfrom 循环中轮询它,以查看是否已超过所需的超时值。
http://dell5.ma.utexas.edu/cgi- bin/man-cgi?gettimeofday+2
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