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