001/**
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.activemq.util;
018
019import java.net.InetAddress;
020import java.net.UnknownHostException;
021
022public class InetAddressUtil {
023
024        /**
025         * When using the {@link java.net.InetAddress#getHostName()} method in an 
026         * environment where neither a proper DNS lookup nor an <tt>/etc/hosts</tt> 
027         * entry exists for a given host, the following exception will be thrown: 
028         * <code>
029         * java.net.UnknownHostException: &lt;hostname&gt;: &lt;hostname&gt;
030     *  at java.net.InetAddress.getLocalHost(InetAddress.java:1425)
031     *   ...
032         * </code>
033         * Instead of just throwing an UnknownHostException and giving up, this 
034         * method grabs a suitable hostname from the exception and prevents the 
035         * exception from being thrown. If a suitable hostname cannot be acquired
036         * from the exception, only then is the <tt>UnknownHostException</tt> thrown. 
037         * 
038         * @return The hostname 
039         * @throws UnknownHostException
040         * @see {@link java.net.InetAddress#getLocalHost()}
041         * @see {@link java.net.InetAddress#getHostName()}
042         */
043        public static String getLocalHostName() throws UnknownHostException {
044                try {
045                        return (InetAddress.getLocalHost()).getHostName();
046                } catch (UnknownHostException uhe) {
047                        String host = uhe.getMessage(); // host = "hostname: hostname"
048                        if (host != null) {
049                                int colon = host.indexOf(':');
050                                if (colon > 0) {
051                                        return host.substring(0, colon);
052                                }
053                        }
054                        throw uhe;
055                }
056        }
057}