debugjavaMinor
Checking if a port is in use
Viewed 0 times
usecheckingport
Problem
Review this code, which should return
Clarification: "In use" means that the port is already open (and used by another application). I'm trying to find a port number between (49152 and 65535) to open that is available.
true if a port is in use or false if the port is not in use.Clarification: "In use" means that the port is already open (and used by another application). I'm trying to find a port number between (49152 and 65535) to open that is available.
private boolean isPortInUse(String hostName, int portNumber) {
boolean result;
try {
Socket s = new Socket(hostName, portNumber);
s.close();
result = true;
}
catch(Exception e) {
result = false;
}
return(result);
}Solution
Don't test for port-in-use in advance. Just let your application do what it wants to do, and catch the exception there. The situation can change between the time you test and when you actually try to use the port.
Furthermore, if you are trying to write a server application, you can have Java automatically pick a free port for you. From the JavaDoc for
Creates a server socket, bound to the specified port. A port number of 0 means that the port number is automatically allocated, typically from an ephemeral port range. This port number can then be retrieved by calling
Furthermore, if you are trying to write a server application, you can have Java automatically pick a free port for you. From the JavaDoc for
ServerSocket(int):Creates a server socket, bound to the specified port. A port number of 0 means that the port number is automatically allocated, typically from an ephemeral port range. This port number can then be retrieved by calling
getLocalPort.Context
StackExchange Code Review Q#31557, answer score: 8
Revisions (0)
No revisions yet.