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 withEADDRINUSE
, 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...