1 23 24 package com.sun.enterprise.admin.common; 25 26 import java.util.Random ; 27 28 import java.net.ServerSocket ; 29 import java.io.IOException ; 30 import com.sun.enterprise.admin.common.exception.PortInUseException; 31 import com.sun.enterprise.admin.util.Debug; 32 33 import com.sun.enterprise.admin.util.SOMLocalStringsManager; 35 36 39 40 41 public class NetUtil 42 { 43 public static final int kMaxPortNo = 65535; 44 45 50 51 public static void checkPortAvailability(int port) throws PortInUseException 52 { 53 ServerSocket trialSocket = null; 54 try 55 { 56 trialSocket = new ServerSocket (port); 57 } 58 catch(IOException ioe) 59 { 60 String msg = localizedStrMgr.getString( "admin.common.port_in_use", new String ( port + "" ) ); 61 throw new PortInUseException( msg ); 62 } 63 finally 64 { 65 try 66 { 67 if (trialSocket != null) 68 { 69 trialSocket.close(); 70 } 71 } 72 catch(Exception e) 73 { 74 Debug.printStackTrace(e); 75 } 76 } 77 } 78 79 85 86 public static boolean isPortAvalable(int portNo) 87 { 88 boolean available = true; 89 90 try 91 { 92 checkPortAvailability(portNo); 93 } 94 catch(Exception e) 95 { 96 available = false; 97 } 98 return ( available ); 99 } 100 101 private static Random random = new Random (); 102 103 private static SOMLocalStringsManager localizedStrMgr = 105 SOMLocalStringsManager.getManager( NetUtil.class ); 106 107 public static int getFreePort() 108 { 109 synchronized(NetUtil.class) 110 { 111 112 for (int i = 0; i < 1024; i++) 113 { 114 int nextInt = random.nextInt(kMaxPortNo); 115 if (nextInt <= 1024) 116 { 117 continue; 118 } 119 else if (isPortAvalable(nextInt)) 120 { 121 return nextInt; 122 } 123 } 124 } 125 return 0; 126 } 127 } 128 | Popular Tags |