What local port is used when opening a socket connection, and how do I control which port is chosen?

Brian O'Byrne

Starting with Java 1.1 there are constructors to Socket which allow you to choose the local port:

public Socket(String host, int remotePort, InetAddress localAddr, int localPort);
public Socket(InetAddress remoteAddr, int remotePort, InetAddress localAddr, int localPort);
If you don't specify a local port, one will be allocated for you by the operating system - usually an arbitrary unused port number above 1024. You can invoke getLocalPort() on your socket instance to find out what local port was chosen.

[FAQ manager's comment - Note that some APIs which use sockets, e.g. RMI and JavaMail, don't allow you direct access to the underlying socket, so you can't control which local port is selected unless you use your own socket factory to create the sockets.]