1 /**********************************************************************
2 Copyright (c) 2000, 2002 IBM Corp. and others.
3 All rights reserved. This program and the accompanying materials
4 are made available under the terms of the Common Public License v1.0
5 which accompanies this distribution, and is available at
6 http://www.eclipse.org/legal/cpl-v10.html
9 IBM Corporation - Initial implementation
10 Vicente Fernando - www.alfersoft.com.ar
11 **********************************************************************/
12 package net.sourceforge.phpdt.internal.debug.core;
14 import java.io.IOException;
15 import java.net.ConnectException;
16 import java.net.Socket;
17 import java.util.Random;
20 * Utility class to find a port to debug on.
22 public class SocketUtil {
23 private static final Random fgRandom= new Random(System.currentTimeMillis());
26 * Returns a free port number on the specified host within the given range,
27 * or -1 if none found.
29 * @param host name or IP addres of host on which to find a free port
30 * @param searchFrom the port number from which to start searching
31 * @param searchTo the port number at which to stop searching
32 * @return a free port in the specified range, or -1 of none found
34 public static int findUnusedLocalPort(String host, int searchFrom, int searchTo) {
36 // First look at the five first ports starting on searchFrom
37 for (int i= searchFrom; i <= searchFrom + 5; i++) {
41 s= new Socket(host, port);
42 } catch (ConnectException e) {
44 } catch (IOException e) {
49 } catch (IOException ioe) {
54 // No free port found then look at 5 random ports numbers
55 for (int i= 0; i < 5; i++) {
57 int port= getRandomPort(searchFrom, searchTo);
59 s= new Socket(host, port);
60 } catch (ConnectException e) {
62 } catch (IOException e) {
67 } catch (IOException ioe) {
75 private static int getRandomPort(int low, int high) {
76 return (int)(fgRandom.nextFloat() * (high-low)) + low;