Home > DeveloperSection > Forums > How would I choose in java that which port is free to use for ServerSocket or Socket?
Linda Perla
Linda Perla

Total Post:13

Posted on    December-01-2015 12:47 AM

 Java Java 

 1 Reply(s)
 380  View(s)
Rate this:
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?

Mayank Tripathi
Mayank Tripathi

Total Post:397

Posted on    December-01-2015 1:03 AM

You wouldn't need to check. You would specify port 0, which causes the system to give you a free port.
Yes , It is given the IP address that the peer connected to, and the same port as the listening socket.
No we won't need to specify the port and IP address.

You can use the java.net.ServerSocket constructor with port 0 which tells ServerSocket to find a free port.
Example :
int port = -1;
try {
    ServerSocket socket = new ServerSocket(0);
    // here's your free port
    port = socket.getLocalPort();

catch (IOException ioe) {}

Also, we can use Use Try catch to find a free port:
private static int port=9000;
public static int detectPort(int prt)
//connect to port
catch(Exception e)
return detectPort(prt+1);
return prt;
// Write detectPort(port); inside main

Don't want to miss updates? Please click the below button!

Follow MindStick