KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > axis > utils > NetworkUtils


1 /*
2  * Copyright 2004 The Apache Software Foundation.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */

16
17 package org.apache.axis.utils;
18
19 import org.apache.commons.logging.Log;
20 import org.apache.axis.components.logger.LogFactory;
21
22 import java.net.InetAddress JavaDoc;
23 import java.net.UnknownHostException JavaDoc;
24
25 /**
26  * Utility classes for networking
27  * created 13-May-2004 16:17:51
28  */

29
30 public class NetworkUtils {
31     /**
32      * what we return when we cannot determine our hostname.
33      * We use this rather than 'localhost' as if DNS is very confused,
34      * localhost can map to different machines than "self".
35      */

36     public static final String JavaDoc LOCALHOST = "127.0.0.1";
37
38     /**
39      * keep this uninstantiable.
40      */

41     private NetworkUtils() {
42     }
43
44     protected static Log log =
45             LogFactory.getLog(NetworkUtils.class.getName());
46
47     /**
48      * Get the string defining the hostname of the system, as taken from
49      * the default network adapter of the system. There is no guarantee that
50      * this will be fully qualified, or that it is the hostname used by external
51      * machines to access the server.
52      * If we cannot determine the name, then we return the default hostname,
53      * which is defined by {@link #LOCALHOST}
54      * @return a string name of the host.
55      */

56     public static String JavaDoc getLocalHostname() {
57         InetAddress JavaDoc address;
58         String JavaDoc hostname;
59         try {
60             address = InetAddress.getLocalHost();
61             //force a best effort reverse DNS lookup
62
hostname = address.getHostName();
63             if (hostname == null || hostname.length() == 0) {
64                 hostname = address.toString();
65             }
66         } catch (UnknownHostException JavaDoc noIpAddrException) {
67
68             //this machine is not on a LAN, or DNS is unhappy
69
//return the default hostname
70
if(log.isDebugEnabled()) {
71                 log.debug("Failed to lookup local IP address",noIpAddrException);
72             }
73             hostname = LOCALHOST;
74         }
75         return hostname;
76     }
77 }
78
Popular Tags