0
votes

Is there a simple (non-iterative) way to bind two sockets, one TCP and one UDP, that guarantees both have the same ephemeral port?

I have a simple server that's connected to via TCP initially, but also transmits over UDP. I don't want to send a UDP packet post-connect from the client just for the server to discover the client's UDP ephemeral port. I don't want to send the port number via the initial TCP connection message unless I have to.

Right now I explicitly bind the client UDP socket's port after a getsockname on the TCP socket to discover the OS-assigned ephemeral port. It hasn't failed yet, but it feels fragile.

Edit: To clarify, the current implementation assumes that the operating system will never assign an ephemeral port for a TCP socket that is already used by a UDP socket.

1
What do you need that port for? What are you trying to do?CodeCaster
It doesn't matter. There are many ways to notify the server of a second ephemeral port without sending data, but I don't want to do any of them if I can help it.Cat Zimmermann
It does matter to me, because I'm curious about what you want to do. Why do two ephemeral ports (i.e. ports that the client OS assigns as source port for a connection or data stream) have to be the same? What benefit is gained doing that and what is wrong with random ports assigned by the OS?CodeCaster
Notifying the server of the second ephemeral port just adds complexity. If you send the second port number over the first TCP connection it's more code on both the client and server. If you send a connection datagram via UDP it's unreliable and adds more code.Cat Zimmermann

1 Answers

0
votes

Bind one to (0), then get the local port value, then bind the other to that value. If it fails (port already allocated), close the first socket, rinse, and repeat.

There's no other way, fragile as it may 'feel'. But I don't see why you need them to be the same. If they're ephemeral, nobody else knows what they are anyway, you have to advertise them somehow.