Here is a minimalist Java code which can be used to test if a port is available.
In this example, we are checking for port 8080 by opening a new Socket to that port. We allow up to 10 retries if the port has been found already used. Enjoy it!
import java.io.IOException;
import java.net.Socket;
public class Portchecker {
private static boolean available(int port) {
System.out.println("--------------Testing port " + port);
Socket s = null;
try {
s = new Socket("localhost", port);
// If the code makes it this far without an exception it means
// something is using the port and has responded.
System.out.println("--------------Port " + port + " is not available");
return false;
} catch (IOException e) {
System.out.println("--------------Port " + port + " is available");
return true;
} finally {
if (s != null) {
try {
s.close();
} catch (IOException e) {
throw new RuntimeException("You should handle this error.", e);
}
}
}
}
public static void main(String[] args) {
int attempts = 0;
boolean scanning = true;
while (scanning) {
if (!available(8080)) {
attempts++;
if (attempts == 10) {
System.out.println("giving up!");
scanning = false;
}
} else {
scanning = false;
}
try {
Thread.sleep(2000);// 2 seconds
} catch (InterruptedException ie) {
ie.printStackTrace();
}
}
}
}