static public int getFreeServerPort ( int port ) { int resultPort = 0 ; ServerSocket s ; try { s = new ServerSocket ( port ) ; resultPort = s . getLocalPort ( ) ; s . close ( ) ; } catch ( IOException e ) { resultPort = 0 ; } return resultPort ; }
Get a free server port that can be used . A preferred port number can be specified . Be aware that this method is not safe if there are so many programs trying to open server sockets .