Java Host Check normalizeHost(String host)

Here you can find the source of normalizeHost(String host)

Description

normalize Host

License

Apache License

Declaration

public static String normalizeHost(String host) 

Method Source Code

//package com.java2s;
/**//  w  ww  .  j ava2s  . co  m
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import java.net.*;

public class Main {
    public static String normalizeHost(String host) {
        try {
            InetAddress address = InetAddress.getByName(host);
            if (isLocalAddress(address)) {
                return InetAddress.getLocalHost().getHostAddress();
            } else {
                return address.getHostAddress();
            }
        } catch (UnknownHostException e) {
        }
        return host;
    }

    /**
     * Given an InetAddress, checks to see if the address is a local address, by
     * comparing the address with all the interfaces on the node.
     * @param addr address to check if it is local node's address
     * @return true if the address corresponds to the local node
     */
    public static boolean isLocalAddress(InetAddress addr) {
        // Check if the address is any local or loop back
        boolean local = addr.isAnyLocalAddress() || addr.isLoopbackAddress();

        // Check if the address is defined on any interface
        if (!local) {
            try {
                local = NetworkInterface.getByInetAddress(addr) != null;
            } catch (SocketException e) {
                local = false;
            }
        }
        return local;
    }
}

Related

  1. isLocal(final String hostname)
  2. isLocal(final String hostName)
  3. isHostReachable(String host, int timeout)
  4. isInternalHostname(String host)
  5. isThisMe(String hostname)
  6. normalizeHostName(String name)
  7. normalizeHostNames(Collection names)