Bilal Rafique
Bilal Rafique

Reputation: 294

How would I choose in java that which port is free to use for ServerSocket or Socket?

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?

Upvotes: 5

Views: 3290

Answers (5)

Bian Jiaping
Bian Jiaping

Reputation: 966

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

};

Upvotes: 1

Alex Panov
Alex Panov

Reputation: 788

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();

Upvotes: 1

user207421
user207421

Reputation: 310884

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.

Upvotes: 0

R. Oosterholt
R. Oosterholt

Reputation: 8080

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) {}

Upvotes: 8

waders group
waders group

Reputation: 538

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

Upvotes: 2

Related Questions