KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > eclipse > tomcat > internal > SocketUtil


1 /*******************************************************************************
2  * Copyright (c) 2000, 2006 IBM Corporation and others.
3  * All rights reserved. This program and the accompanying materials
4  * are made available under the terms of the Eclipse Public License v1.0
5  * which accompanies this distribution, and is available at
6  * http://www.eclipse.org/legal/epl-v10.html
7  *
8  * Contributors:
9  * IBM Corporation - initial API and implementation
10  *******************************************************************************/

11 package org.eclipse.tomcat.internal;
12
13 import java.io.*;
14 import java.net.*;
15 import java.util.*;
16
17 /**
18  * Utility class to find a port for local help.
19  */

20 public class SocketUtil {
21     private static final Random random = new Random(System.currentTimeMillis());
22
23     /**
24      * Returns a free port number, or -1 if none found.
25      */

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