如何找到空闲的 UDP 端口对? [英] How do you locate a free UDP port pair?

查看:82
本文介绍了如何找到空闲的 UDP 端口对?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

RTP 规范规定,给定 RTP 流的 RTCP 数据包将在主 RTP 端口的 +1 端口上发送.因此,例如,如果您的视频到达 RTP 端口 9010,然后到达端口 9011,您可以期待 RTCP 数据包.

当我协商单播流(通过 RTSP 协议)时,我必须建议我希望视频发送给我的端口对(1 个用于 RTP,1 个用于 RTCP)...

现在,我知道如果我绑定一个端口为 0 的套接字,系统将从临时范围中选择一个空闲端口......我的问题是我实际上需要一对端口,我需要RTCP端口是RTP端口的+1(其实我觉得我需要RTP端口是偶数).

有没有办法定位一对空闲端口?这通常是如何完成的?

解决方案

你得到一个随机的,然后尝试下一个.

如果第二个端口上的 bind() 调用失败并显示 EADDRINUSE,请冲洗并重复...

无论如何,在大多数系统上,如果两个调用足够接近,您可能不必重复序列.

临时端口通常是按顺序分配的,因此下一个端口不会空闲的唯一方法是该端口已被长期进程使用(不太可能在 UDP 上),或者其他人偷偷溜进bind() 在你们两个之间调用.

同样,如果您需要 RTP 端口为偶数,请先随机选择第一个端口,如果返回奇数端口,请再试一次 - 根据上述内容,下一个端口可能是偶数!如果没有,请冲洗并重复...

The RTP specification says that the RTCP packets for a given RTP stream will be sent on a port that is +1 of the main RTP port. So for example, if you have video arriving on RTP port 9010, then on port 9011, you can expect RTCP packets.

When I'm negotiating a unicast stream (via the RTSP protocol), I have to suggest pair of ports that I would like the video sent to me on (1 for RTP, and 1 for RTCP)...

Now, I know that if I bind a socket with a port of 0, the system will pick a free port from the ephemeral range... The problem I have is that I actually need a pair of ports, and I need the RTCP port to be +1 of the RTP port (in fact, I think I need the RTP port to be an even number).

Is there a way to locate a pair of free ports? How is this normally done?

解决方案

You get a random one, then try the next one up.

If the bind() call on the second port fails with EADDRINUSE, rinse and repeat...

For what it's worth, on most systems if the two calls are close enough you'll likely not have to repeat the sequence.

Ephemeral ports are usually assigned sequentially, so the only way the next port won't be free will be if either the port was already being used by a long-lived process (unlikely on UDP) or if someone else snuck in a bind() call in between your two.

Likewise, if you need the RTP port to be even, just go random for the first, and if that returns an odd port just try again - per the above, chances are the next port will be even! If not, rinse and repeat...

这篇关于如何找到空闲的 UDP 端口对?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆