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
24 .currentTimeMillis());
27 * Returns a free port number on the specified host within the given range,
28 * or -1 if none found.
31 * name or IP addres of host on which to find a free port
33 * the port number from which to start searching
35 * the port number at which to stop searching
36 * @return a free port in the specified range, or -1 of none found
38 public static int findUnusedLocalPort(String host, int searchFrom,
41 // First look at the five first ports starting on searchFrom
42 for (int i = searchFrom; i <= searchFrom + 5; i++) {
46 s = new Socket(host, port);
47 } catch (ConnectException e) {
49 } catch (IOException e) {
54 } catch (IOException ioe) {
59 // No free port found then look at 5 random ports numbers
60 for (int i = 0; i < 5; i++) {
62 int port = getRandomPort(searchFrom, searchTo);
64 s = new Socket(host, port);
65 } catch (ConnectException e) {
67 } catch (IOException e) {
72 } catch (IOException ioe) {
80 private static int getRandomPort(int low, int high) {
81 return (int) (fgRandom.nextFloat() * (high - low)) + low;