Search code examples
javaportserversocket

Java ServerSocket closed port


I am making a simple Server application.I wanted to know if there is any way to know if the port that user enters in the application ,in order to make new ServerScoket that's listening to this port , is closed?Say,someone enters port 5000 that's closed,is there any way to check it and inform the user that he/she is trying to use closed port?

I want to do something like this :

int port = Integer.parseInt(portField.getText()); // the port that users enter in my application

if ( port.isClosed() ) {
    System.out.println("This port is closed.Try another!");
}

isClose is a method that checks whether the port is closed or not.By "closed" i mean that the user hasn't done port forwarding.


Solution

  • Not in Java. You could write a WMIC command or something that examines the local firewall rules, but if the port is closed by an external router even that won't work. You should choose a fixed local port yourself and instruct the user that they must open the port, via whatever means are locally applicable.