1 11 package org.eclipse.jdt.launching; 12 13 14 import java.io.IOException ; 15 import java.net.ConnectException ; 16 import java.net.ServerSocket ; 17 import java.net.Socket ; 18 import java.util.Random ; 19 20 26 public class SocketUtil { 27 private static final Random fgRandom= new Random (System.currentTimeMillis()); 28 29 41 public static int findUnusedLocalPort(String host, int searchFrom, int searchTo) { 42 43 for (int i= 0; i < 10; i++) { 44 Socket s= null; 45 int port= getRandomPort(searchFrom, searchTo); 46 try { 47 s= new Socket (host, port); 48 } catch (ConnectException e) { 49 return port; 50 } catch (IOException e) { 51 } finally { 52 if (s != null) { 53 try { 54 s.close(); 55 } catch (IOException ioe) { 56 } 57 } 58 } 59 } 60 return -1; 61 } 62 63 private static int getRandomPort(int low, int high) { 64 return (int)(fgRandom.nextFloat() * (high-low)) + low; 65 } 66 67 73 public static int findFreePort() { 74 ServerSocket socket= null; 75 try { 76 socket= new ServerSocket (0); 77 return socket.getLocalPort(); 78 } catch (IOException e) { 79 } finally { 80 if (socket != null) { 81 try { 82 socket.close(); 83 } catch (IOException e) { 84 } 85 } 86 } 87 return -1; 88 } 89 } 90 | Popular Tags |