1 11 package org.eclipse.tomcat.internal; 12 13 import java.io.*; 14 import java.net.*; 15 import java.util.*; 16 17 20 public class SocketUtil { 21 private static final Random random = new Random(System.currentTimeMillis()); 22 23 26 public static int findUnusedLocalPort(InetAddress address) { 27 try { 28 if (address == null) 29 address = InetAddress.getByAddress(new byte[]{127, 0, 0, 1}); 30 } catch (UnknownHostException uhe) { 31 return -1; 32 } 33 34 int port = findUnusedPort(address, 49152, 65535); 35 if (port == -1) 36 port = findFreePort(); 37 return port; 38 } 39 40 private static int findUnusedPort(InetAddress address, int from, int to) { 41 for (int i = 0; i < 12; i++) { 42 ServerSocket ss = null; 43 int port = getRandomPort(from, to); 44 try { 45 ss = new ServerSocket(); 46 SocketAddress sa = new InetSocketAddress(address, port); 47 ss.bind(sa); 48 return ss.getLocalPort(); 49 } catch (IOException e) { 50 } finally { 51 if (ss != null) { 52 try { 53 ss.close(); 54 } catch (IOException ioe) { 55 } 56 } 57 } 58 } 59 return -1; 60 } 61 62 private static int getRandomPort(int low, int high) { 63 return (int) (random.nextFloat() * (high - low)) + low; 64 } 65 66 private static int findFreePort() { 67 ServerSocket socket = null; 68 try { 69 socket = new ServerSocket(0); 70 return socket.getLocalPort(); 71 } catch (IOException e) { 72 } finally { 73 if (socket != null) { 74 try { 75 socket.close(); 76 } catch (IOException e) { 77 } 78 } 79 } 80 return -1; 81 } 82 } 83 | Popular Tags |