KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jboss > remoting > transport > PortUtil


1 /***************************************
2  * *
3  * JBoss: The OpenSource J2EE WebOS *
4  * *
5  * Distributable under LGPL license. *
6  * See terms of license at gnu.org. *
7  * *
8  ***************************************/

9 package org.jboss.remoting.transport;
10
11 import java.net.ServerSocket JavaDoc;
12
13 /**
14  * PortUtil is a set of utilities for dealing with TCP/IP ports
15  *
16  * @author <a HREF="mailto:jhaynie@vocalocity.net">Jeff Haynie</a>
17  * @version $Revision: 1.3 $
18  */

19 public class PortUtil
20 {
21    private static final int START_PORT_RANGE = Integer.parseInt(System.getProperty("jboss.remoting.start.portrange", "5000"));
22    private static int lastPort = START_PORT_RANGE;
23
24    /**
25     * Checks to see if the specified port is free.
26     *
27     * @param p
28     * @return true if available, false if already in use
29     */

30    public static boolean checkPort(int p)
31    {
32       ServerSocket JavaDoc socket = null;
33       try
34       {
35          // try and open port,
36
socket = new ServerSocket JavaDoc(p);
37
38          return true;
39       }
40       catch(Exception JavaDoc ex)
41       {
42       }
43       finally
44       {
45          if(socket != null)
46          {
47             try
48             {
49                socket.close();
50             }
51             catch(Exception JavaDoc ig)
52             {
53             }
54             socket = null;
55          }
56       }
57       return false;
58    }
59
60    public static int findFreePort()
61    {
62       if(lastPort > 64000)
63       {
64          lastPort = START_PORT_RANGE;
65       }
66       //start where we left off
67
for(int c = lastPort; c < 64000; c++)
68       {
69          if(checkPort(c))
70          {
71             lastPort = c + 1;
72             return c;
73          }
74       }
75       // start back at top
76
for(int c = START_PORT_RANGE; c < lastPort; c++)
77       {
78          if(checkPort(c))
79          {
80             lastPort = c + 1;
81             return c;
82          }
83       }
84       throw new RuntimeException JavaDoc("Couldn't find a free TCP/IP port");
85    }
86
87    public static void main(String JavaDoc args[])
88    {
89       try
90       {
91          System.out.println("port - " + findFreePort());
92       }
93       catch(Exception JavaDoc ex)
94       {
95          ex.printStackTrace();
96       }
97    }
98 }
99
Popular Tags