Can and will an operating system reuse a source port number for a connection to a different destination address/port combination?
If I connect()
to enough hosts, and keep those connections open, eventually I'll run out of unique source ports, exhausting the ephemeral range, the non-root range (1025-65,535; assuming non-root) or the absolute range (0-65,535). I want to know if those represent real limits to the number of hosts I can simultaneously have a connection to. I'm interested in what the standards promise (or don't), as well as the reality on Linux (Windows would be a bonus).
I know that opening that many connections will likely run into a number of other limits; that's a different issue and question. If it matters, this massive number of connections would be divided among a similarly large number of processes. I'm interested in the case where I'm requesting an ephemeral port, not manually bind()
ing one. If under "normal" circumstances ports won't be reused, are there ways of changing that behavior from user-space (at which point bind()
ing to a specific point becomes an option)?
Techopedia Explains Ephemeral Port After communication is terminated, the port becomes available for use in another session. However, it is usually reused only after the entire port range is used up.
Each time a client process initiates a UDP or TCP communication it is assigned a temporary, or ephemeral, port number to use for that conversation. These port numbers are assigned in a pseudo-random way, since the exact number used is not important, as long as each process has a different number.
It is the client's operating system that chooses the sender's port from the ephemeral port range and this range varies depending on the OS. For example, many Linux kernels including Amazon Linux kernel use port 32768-61000.
By default, the kernel will not reuse any in-use port for an ephemeral port, which may result in failures if you have 64K+ simultaneous ports in use.
You can explicitly reuse a port by using the SO_REUSEADDR
socket option and explicitly binding to the same port. This only works if none of the ports are listening (you can't reuse a listening port), and if you connect each socket to a different remote address.
In theory yes. In practice no, because bind precedes connect, and so it can't see what you're connecting to, so can't see that the 4-tuple would be unique, so won't let you reuse an ephemeral port.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With