I'm working on java. How would I check that a port is free to use for a ServerSocket
?
Moreover when a Socket is returned by the accept()
function is it given a port and IP address by default or I would have to specify that too?

- 7,720
- 2
- 53
- 77

- 304
- 3
- 18
-
[This](http://stackoverflow.com/questions/434718/sockets-discover-port-availability-using-java) might help. – Bubletan Jul 07 '15 at 19:49
-
Note you should limit the ports you choose from to the [dynamic / private port range](https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Dynamic.2C_private_or_ephemeral_ports), so 49152–65535. – dimo414 Jul 08 '15 at 03:51
5 Answers
You can use the java.net.ServerSocket
constructor with port 0
which tells ServerSocket
to find a free port.
port - the port number, or 0 to use a port number that is automatically allocated.
Example:
int port = -1;
try {
ServerSocket socket = new ServerSocket(0);
// here's your free port
port = socket.getLocalPort();
socket.close();
}
catch (IOException ioe) {}

- 7,720
- 2
- 53
- 77
Use Try catch to find a free port
private static int port=9000;
public static int detectPort(int prt)
{
try{
//connect to port
}
catch(Exception e)
{
return detectPort(prt+1);
}
return prt;
}
// Write detectPort(port); inside main

- 538
- 3
- 7
-
`detectPort(prt++);` will result in an infinite loop, right? Using `prt+1` would be better, I think. – JackWhiteIII Jul 07 '15 at 20:46
-
-
1Recursion risks a stack overflow here, simpler to just use a loop. You shouldn't be grabbing any ports lower than 49152, as well. – dimo414 Jul 08 '15 at 04:37
-
1Complete waste of time and space. Specifying zero will give you a free port without any retrying at all. – user207421 Dec 01 '15 at 08:38
I have released a tiny library for doing just that with tests in mind. Maven dependency is:
<dependency>
<groupId>me.alexpanov</groupId>
<artifactId>free-port-finder</artifactId>
<version>1.0</version>
</dependency>
Once installed, free port numbers can be obtained via:
int port = FreePortFinder.findFreeLocalPort();

- 758
- 10
- 11
We can refer to how Spring's SocketUtils works.
The key idea is to generate a random port, check whether it's available, and repeat until an available port is found.
private enum SocketType {
TCP {
@Override
protected boolean isPortAvailable(int port) {
try {
ServerSocket serverSocket = ServerSocketFactory.getDefault().createServerSocket(
port, 1, InetAddress.getByName("localhost"));
serverSocket.close();
return true;
}
catch (Exception ex) {
return false;
}
}
},
UDP {
@Override
protected boolean isPortAvailable(int port) {
try {
DatagramSocket socket = new DatagramSocket(port, InetAddress.getByName("localhost"));
socket.close();
return true;
}
catch (Exception ex) {
return false;
}
}
};

- 946
- 8
- 20
How would I check that a port is free to use for a ServerSocket?
You wouldn't. You would specify port 0, which causes the system to give you a free port.
Moreover when a Socket is returned by the accept() function is it given a port and IP address by default
Yes. It is given the IP address that the peer connected to, and the same port as the listening socket.
or I would have to specify that too?
No.

- 305,947
- 44
- 307
- 483