KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sun > enterprise > util > net > NetUtils


1 /*
2  * The contents of this file are subject to the terms
3  * of the Common Development and Distribution License
4  * (the License). You may not use this file except in
5  * compliance with the License.
6  *
7  * You can obtain a copy of the license at
8  * https://glassfish.dev.java.net/public/CDDLv1.0.html or
9  * glassfish/bootstrap/legal/CDDLv1.0.txt.
10  * See the License for the specific language governing
11  * permissions and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL
14  * Header Notice in each file and include the License file
15  * at glassfish/bootstrap/legal/CDDLv1.0.txt.
16  * If applicable, add the following below the CDDL Header,
17  * with the fields enclosed by brackets [] replaced by
18  * you own identifying information:
19  * "Portions Copyrighted [year] [name of copyright owner]"
20  *
21  * Copyright 2006 Sun Microsystems, Inc. All rights reserved.
22  */

23
24 /*
25  * Copyright 2004-2005 Sun Microsystems, Inc. All rights reserved.
26  * Use is subject to license terms.
27  */

28
29 /*
30  * NetUtils.java
31  *
32  * Created on April 2, 2002, 9:19 PM
33  *
34  * @author bnevins
35  * @version $Revision: 1.4 $
36  * <BR> <I>$Source: /cvs/glassfish/appserv-commons/src/java/com/sun/enterprise/util/net/NetUtils.java,v $
37  *
38  * Copyright 2000-2001 by iPlanet/Sun Microsystems, Inc.,
39  * 901 San Antonio Road, Palo Alto, California, 94303, U.S.A.
40  * All rights reserved.
41  *
42  * This software is the confidential and proprietary information
43  * of iPlanet/Sun Microsystems, Inc. ("Confidential Information").
44  * You shall not disclose such Confidential Information and shall
45  * use it only in accordance with the terms of the license
46  * agreement you entered into with iPlanet/Sun Microsystems.
47  *
48  */

49
50 package com.sun.enterprise.util.net;
51 import java.net.*;
52 import java.util.*;
53 import java.io.*;
54
55 public class NetUtils
56 {
57     private NetUtils()
58     {
59     }
60     
61     public static final int MAX_PORT = 65535;
62     
63     ///////////////////////////////////////////////////////////////////////////
64

65     public static String JavaDoc getHostName()
66     {
67         try
68         {
69             return InetAddress.getLocalHost().getHostName();
70         }
71         catch(Exception JavaDoc e)
72         {
73             return null;
74         }
75     }
76
77         ///////////////////////////////////////////////////////////////////////////
78

79         
80     /**
81          * This method returns the fully qualified name of the host. If
82          * the name can't be resolved (on windows if there isn't a domain specified), just
83          * host name is returned
84          *
85          * @throws UnknownHostException so it can be handled on a case by case basis
86          */

87         public static String JavaDoc getCanonicalHostName() throws UnknownHostException {
88             String JavaDoc hostname=null;
89             String JavaDoc defaultHostname=InetAddress.getLocalHost().getHostName();
90             // look for full name
91
hostname=InetAddress.getLocalHost().getCanonicalHostName();
92
93             // check to see if ip returned or canonical hostname is different than hostname
94
// It is possible for dhcp connected computers to have an erroneous name returned
95
// that is created by the dhcp server. If that happens, return just the default hostname
96
if (hostname.equals(InetAddress.getLocalHost().getHostAddress()) ||
97                 !hostname.startsWith(defaultHostname)) {
98                 // don't want IP or canonical hostname, this will cause a lot of problems for dhcp users
99
// get just plan host name instead
100
hostname=defaultHostname;
101             }
102             
103             return hostname;
104     }
105     
106     ///////////////////////////////////////////////////////////////////////////
107

108     public static InetAddress[] getHostAddresses()
109     {
110         try
111         {
112             String JavaDoc hname = getHostName();
113             
114             if(hname == null)
115                 return null;
116             
117             return InetAddress.getAllByName(hname);
118         }
119         catch(Exception JavaDoc e)
120         {
121             return null;
122         }
123     }
124     
125     ///////////////////////////////////////////////////////////////////////////
126

127     public static String JavaDoc[] getHostIPs()
128     {
129         try
130         {
131             InetAddress[] adds = getHostAddresses();
132             
133             if(adds == null)
134                 return null;
135
136             String JavaDoc[] ips = new String JavaDoc[adds.length];
137             
138             for(int i = 0; i < adds.length; i++)
139             {
140                 String JavaDoc ip = trimIP(adds[i].toString());
141                 ips[i] = ip;
142             }
143             
144             return ips;
145         }
146         catch(Exception JavaDoc e)
147         {
148             return null;
149         }
150     }
151     
152     ///////////////////////////////////////////////////////////////////////////
153

154     public static String JavaDoc trimIP(String JavaDoc ip)
155     {
156         if(ip == null || ip.length() <= 0)
157             return ip;
158         
159         int index = ip.lastIndexOf('/');
160
161         if(index >= 0)
162             return ip.substring(++index);
163         
164         return ip;
165     }
166         
167     ///////////////////////////////////////////////////////////////////////////
168

169     public static byte[] ip2bytes(String JavaDoc ip)
170     {
171         try
172         {
173             // possibilities: "1.1.1.1", "frodo/1.1.1.1", "frodo.foo.com/1.1.1.1"
174

175             ip = trimIP(ip);
176             StringTokenizer stk = new StringTokenizer(ip, ".");
177
178             byte[] bytes = new byte[stk.countTokens()];
179
180             for(int i = 0; stk.hasMoreTokens(); i++)
181             {
182                 String JavaDoc num = stk.nextToken();
183                 int inum = Integer.parseInt(num);
184                 bytes[i] = (byte)inum;
185                 //System.out.println("token: " + inum);
186
}
187             return bytes;
188         }
189         catch(NumberFormatException JavaDoc nfe)
190         {
191             return null;
192         }
193     }
194     
195     ///////////////////////////////////////////////////////////////////////////
196

197     public static boolean isLocalHost(String JavaDoc ip)
198     {
199         if(ip == null)
200             return false;
201         
202         ip = trimIP(ip);
203         
204         return ip.equals(LOCALHOST_IP);
205     }
206     
207     ///////////////////////////////////////////////////////////////////////////
208

209     public static boolean isLocal(String JavaDoc ip)
210     {
211         if(ip == null)
212             return false;
213         
214         ip = trimIP(ip);
215         
216         if(isLocalHost(ip))
217             return true;
218         
219         String JavaDoc[] myIPs = getHostIPs();
220         
221         if(myIPs == null)
222             return false;
223         
224         for(int i = 0; i < myIPs.length; i++)
225         {
226             if(ip.equals(myIPs[i]))
227                 return true;
228         }
229         
230         return false;
231     }
232     
233     ///////////////////////////////////////////////////////////////////////////
234

235     public static boolean isRemote(String JavaDoc ip)
236     {
237         return !isLocal(ip);
238     }
239     
240     
241     /**
242      * Get the next free port (incrementing by 1)
243      * @param hostName The host name on which the port is to be obtained
244      * @param port The port number
245      * @return The next incremental port number or 0 if a port cannot be found.
246      */

247     public static int getNextFreePort(String JavaDoc hostName, int port)
248     {
249         while (port++ < MAX_PORT) {
250             if (isPortFree(hostName, port)) {
251                 return port;
252             }
253         }
254         return 0;
255     }
256     
257     /**
258      * Returns a random port in the specified range
259      * @param hostName The host on which the port is to be obtained.
260      * @param startingPort starting port in the range
261      * @param endingPort ending port in the range
262      * @return the new port or 0 if the range is invalid.
263      */

264     public static int getFreePort(String JavaDoc hostName, int startingPort, int endingPort)
265     {
266         int range = endingPort - startingPort;
267         int port = 0;
268         if (range > 0) {
269             Random r = new Random();
270             while (true) {
271                 port = r.nextInt(range + 1) + startingPort;
272                 if (isPortFree(hostName, port)) {
273                     break;
274                 }
275             }
276         }
277         return port;
278     }
279
280     public static boolean isPortValid(int portNumber)
281     {
282         if (portNumber >=0 && portNumber <= MAX_PORT) {
283             return true;
284         } else {
285             return false;
286         }
287     }
288
289     public static boolean isPortStringValid(String JavaDoc portNumber)
290     {
291         try {
292             return isPortValid(Integer.parseInt(portNumber));
293         } catch (NumberFormatException JavaDoc ex) {
294             return false;
295         }
296     }
297     
298     ///////////////////////////////////////////////////////////////////////////
299

300     public static boolean isPortFree(String JavaDoc hostName, int portNumber)
301     {
302         if(portNumber <= 0 || portNumber > MAX_PORT)
303             return false;
304         
305         if(hostName == null || isThisMe(hostName))
306             return isPortFreeServer(portNumber);
307         else
308             return isPortFreeClient(hostName, portNumber);
309     }
310     
311     public static boolean isPortFree(int portNumber)
312     {
313         return isPortFree(null, portNumber);
314     }
315     
316     private static boolean isPortFreeClient(String JavaDoc hostName, int portNumber)
317     {
318         try
319         {
320             // WBN - I have no idea why I'm messing with these streams!
321
// I lifted the code from installer. Apparently if you just
322
// open a socket on a free port and catch the exception something
323
// will go wrong in Windows.
324
// Feel free to change it if you know EXACTLY what you'return doing
325

326             //If the host name is null, assume localhost
327
if (hostName == null) {
328                 hostName = getHostName();
329             }
330             Socket socket = new Socket(hostName, portNumber);
331             OutputStream os = socket.getOutputStream();
332             InputStream is = socket.getInputStream();
333             os.close();
334             os = null;
335             is.close();
336             is = null;
337             socket.close();
338             socket = null;
339         }
340         catch (Exception JavaDoc e)
341         {
342             // Nobody is listening on this port
343
return true;
344         }
345     
346         return false;
347     }
348
349     private static boolean isPortFreeServer(int port)
350     {
351         try
352         {
353             ServerSocket ss = new ServerSocket(port);
354             ss.close();
355             return true;
356         }
357         catch (Exception JavaDoc e)
358         {
359             return false;
360         }
361     }
362     
363     
364     /**
365         Gets a free port at the time of call to this method.
366         The logic leverages the built in java.net.ServerSocket implementation
367         which binds a server socket to a free port when instantiated with
368         a port <code> 0 </code>.
369         <P> Note that this method guarantees the availability of the port
370         only at the time of call. The method does not bind to this port.
371         <p> Checking for free port can fail for several reasons which may
372         indicate potential problems with the system. This method acknowledges
373         the fact and following is the general contract:
374         <li> Best effort is made to find a port which can be bound to. All
375         the exceptional conditions in the due course are considered SEVERE.
376         <li> If any exceptional condition is experienced, <code> 0 </code>
377         is returned, indicating that the method failed for some reasons and
378         the callers should take the corrective action. (The method need not
379         always throw an exception for this).
380         <li> Method is synchronized on this class.
381         @return integer depicting the free port number available at this time
382         0 otherwise.
383     */

384     public static int getFreePort()
385     {
386         int freePort = 0;
387         boolean portFound = false;
388         ServerSocket serverSocket = null;
389
390         synchronized (NetUtils.class)
391         {
392             try
393             {
394                 /*following call normally returns the free port,
395                   to which the ServerSocket is bound. */

396                 serverSocket = new ServerSocket(0);
397                 freePort = serverSocket.getLocalPort();
398                 portFound = true;
399             }
400             catch(Exception JavaDoc e)
401             {
402                 //squelch the exception
403
}
404             finally
405             {
406                 if (!portFound)
407                 {
408                     freePort = 0;
409                 }
410                 try
411                 {
412                     if (serverSocket != null)
413                     {
414                         serverSocket.close();
415                         if (! serverSocket.isClosed())
416                         {
417                             throw new Exception JavaDoc("local exception ...");
418                         }
419                     }
420                 }
421                 catch(Exception JavaDoc e)
422                 {
423                     //squelch the exception
424
freePort = 0;
425                 }
426             }
427             return freePort;
428         }
429     }
430
431     ///////////////////////////////////////////////////////////////////////////
432

433     private static final String JavaDoc LOCALHOST_IP = "127.0.0.1";
434     
435     ///////////////////////////////////////////////////////////////////////////
436

437     private static boolean isThisMe(String JavaDoc hostname)
438     {
439         try
440         {
441             InetAddress[] myadds = getHostAddresses();
442             InetAddress[] theiradds = InetAddress.getAllByName(hostname);
443             
444             for(int i = 0; i < theiradds.length; i++)
445             {
446                 if(theiradds[i].isLoopbackAddress())
447                     return true;
448
449                 for(int j = 0; j < myadds.length; j++)
450                 {
451                     if(myadds[j].equals(theiradds[i]))
452                         return true;
453                 }
454             }
455         }
456         catch(Exception JavaDoc e)
457         {
458         }
459         
460         return false;
461     }
462     
463     ///////////////////////////////////////////////////////////////////////////
464

465     public static void main(String JavaDoc[] args)
466     {
467         System.out.println("80: " + isPortFree(80));
468         System.out.println("777: " + isPortFree(777));
469         System.out.println("8000: " + isPortFree(8000));
470     }
471 }
472
473
474
475
Popular Tags