Question:
I need to take a port number as input froma user. How can I check if the port numberentered by the user is free and not beingused by any program currently on his/her machine?
Answer:
The only way to do this in pure Java is to try to open a socket on the local port and see if it succeeds. If it fails because the port number is already in use, then the connection attempt will throw a java.io.BindException. An example would look something like this:
ServerSocket socket;try { socket = new ServerSocket(port);} catch(BindException be) { // We failed because port was already in use} catch(IOException ioe) { // Some other error happened}