6

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?

R. Oosterholt
  • 7,720
  • 2
  • 53
  • 77
Bilal Rafique
  • 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 Answers5

9

You can use the java.net.ServerSocket constructor with port 0 which tells ServerSocket to find a free port.

documentation:

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) {}
R. Oosterholt
  • 7,720
  • 2
  • 53
  • 77
2

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
waders group
  • 538
  • 3
  • 7
1

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();
Alex Panov
  • 758
  • 10
  • 11
1

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;
            }
        }

};

Bian Jiaping
  • 946
  • 8
  • 20
0

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.

user207421
  • 305,947
  • 44
  • 307
  • 483