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     */
017    package org.apache.camel.util;
018    
019    import java.net.InetAddress;
020    import java.net.UnknownHostException;
021    
022    /**
023     * Util class for {@link java.net.InetAddress}
024     */
025    public final class InetAddressUtil {
026    
027        private InetAddressUtil() {
028            // util class
029        }
030    
031        /**
032         * When using the {@link java.net.InetAddress#getHostName()} method in an
033         * environment where neither a proper DNS lookup nor an <tt>/etc/hosts</tt>
034         * entry exists for a given host, the following exception will be thrown:
035         * <p/>
036         * <code>
037         * java.net.UnknownHostException: &lt;hostname&gt;: &lt;hostname&gt;
038         * at java.net.InetAddress.getLocalHost(InetAddress.java:1425)
039         * ...
040         * </code>
041         * <p/>
042         * Instead of just throwing an UnknownHostException and giving up, this
043         * method grabs a suitable hostname from the exception and prevents the
044         * exception from being thrown. If a suitable hostname cannot be acquired
045         * from the exception, only then is the <tt>UnknownHostException</tt> thrown.
046         *
047         * @return the hostname
048         * @throws UnknownHostException is thrown if hostname could not be resolved
049         */
050        public static String getLocalHostName() throws UnknownHostException {
051            try {
052                return (InetAddress.getLocalHost()).getHostName();
053            } catch (UnknownHostException uhe) {
054                String host = uhe.getMessage(); // host = "hostname: hostname"
055                if (host != null) {
056                    int colon = host.indexOf(':');
057                    if (colon > 0) {
058                        return host.substring(0, colon);
059                    }
060                }
061                throw uhe;
062            }
063        }
064    
065    }