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?
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) {}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With