Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I reuse (ephemeral) ports connecting to different hosts?

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)?

like image 972
Alan De Smet Avatar asked Apr 25 '14 21:04

Alan De Smet


People also ask

Can I use ephemeral ports?

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.

Are ephemeral ports random?

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.

Who assigns ephemeral port?

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.


2 Answers

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.

like image 55
Chris Dodd Avatar answered Oct 18 '22 23:10

Chris Dodd


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.

like image 36
user207421 Avatar answered Oct 19 '22 00:10

user207421