The code can be simplified somewhat:
private boolean isPortInUse(String host, int port) {
// Assume no connection is possible.
boolean result = false;
try {
(new Socket(host, port)).close();
result = true;
}
catch(SocketException e) {
// Could not connect.
}
return result;
}
Note, however, that if you want to check for an available port, that could be reflected in the method name:
private boolean availablePort(String host, int port) {
// Assume port is available.
boolean result = true;
try {
(new Socket(host, port)).close();
// Successful connection means the port is taken.
result = false;
}
catch(SocketException e) {
// Could not connect.
}
return result;
}
Neither approaches employ object-oriented programming (OOP) techniques, though. In OOP, behaviour (determining port availability) is kept with the object that contains the attributes. For example:
public SocketAnalyzer extends java.net.Socket {
public boolean isPortAvailable() {
// ... code here ...
}
}
Now the initial method simplifies to:
private boolean availablePort(String host, int port) {
return (new SocketAnalyzer(host, port)).isPortAvailable();
}
And that allows the "availablePort" method to be removed completely, if desired:
if( (new SocketAnalyzer(host, port)).isPortAvailable() ) {
// Launch the server socket on 'port'!
}
This promotes re-use, and shows one more idea: you could extend ServerSocket
instead! The code would become:
// The constructor would have to bind to the host/port combination...
// This is arguably poor form as the constructor really shouldn't do anything.
// You could, instead, use the superclass' constructor and then call bind,
// but for the purposes of this example, the idea is key: inherit.
ServerSocketAnalyzer ssa = new ServerSocketAnalyzer( host, port );
if( ssa.isPortAvailable() ) {
// Code to use the server socket...
Socket s = ssa.accept();
}
Clean and simple, but there's a race condition. In between the time it takes to determine whether the port is available and the server starts accepting connections to that port, another service may have started to commandeer the port.
The best solution is to allow the server to pick an available port using an atomic operation, as per the other answer.
Exception
is not a good practice try to catch the known subclass which you expect... \$\endgroup\$