Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

sockets

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?

like image 476
Bilal Rafique Avatar asked Jul 07 '15 19:07

Bilal Rafique


2 Answers

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) {}
like image 153
R. Oosterholt Avatar answered Oct 02 '22 00:10

R. Oosterholt


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
like image 45
waders group Avatar answered Oct 01 '22 23:10

waders group