How do I find a free UDP port pair?

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

When I discuss unicast streaming (over RTSP), I have to suggest a pair of ports that I would like the video to be sent to me (1 for RTP and 1 for RTCP) ...

Now I know that if I bind a socket to port 0, the system will pick a free port from the ephemeral range ... The problem is that I really need a pair of ports and I need the RTCP port to be +1 RTP port (actually, it seems to me that an even number is required for the RTP port).

Is there a way to find a couple of free ports? How is this usually done?


source to share

1 answer

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

If the call bind()

on the second port ends with EADDRINUSE

, rinse and repeat ...

For what it's worth, on most systems, if the two calls are close enough, you probably won't have to repeat the sequence.

Ephemeral ports are usually assigned sequentially, so the only way the next port won't be free would be if either the port was already in use by a long running process (unlikely for UDP), or if someone else bind()

calls between the two.

Likewise, if you need an RTP port to be even, just pick a random one for the first one, and if that returns an odd port, try again - as above, the next port will most likely be even! If not, rinse and repeat ...



All Articles