1 9 package org.jboss.remoting.transport; 10 11 import java.net.ServerSocket ; 12 13 19 public class PortUtil 20 { 21 private static final int START_PORT_RANGE = Integer.parseInt(System.getProperty("jboss.remoting.start.portrange", "5000")); 22 private static int lastPort = START_PORT_RANGE; 23 24 30 public static boolean checkPort(int p) 31 { 32 ServerSocket socket = null; 33 try 34 { 35 socket = new ServerSocket (p); 37 38 return true; 39 } 40 catch(Exception ex) 41 { 42 } 43 finally 44 { 45 if(socket != null) 46 { 47 try 48 { 49 socket.close(); 50 } 51 catch(Exception ig) 52 { 53 } 54 socket = null; 55 } 56 } 57 return false; 58 } 59 60 public static int findFreePort() 61 { 62 if(lastPort > 64000) 63 { 64 lastPort = START_PORT_RANGE; 65 } 66 for(int c = lastPort; c < 64000; c++) 68 { 69 if(checkPort(c)) 70 { 71 lastPort = c + 1; 72 return c; 73 } 74 } 75 for(int c = START_PORT_RANGE; c < lastPort; c++) 77 { 78 if(checkPort(c)) 79 { 80 lastPort = c + 1; 81 return c; 82 } 83 } 84 throw new RuntimeException ("Couldn't find a free TCP/IP port"); 85 } 86 87 public static void main(String args[]) 88 { 89 try 90 { 91 System.out.println("port - " + findFreePort()); 92 } 93 catch(Exception ex) 94 { 95 ex.printStackTrace(); 96 } 97 } 98 } 99 | Popular Tags |