Java Local Host Get getAllLocalHostNames()

Here you can find the source of getAllLocalHostNames()

Description

get All Local Host Names

License

Apache License

Return

All known local names for this host or null if none found.

Declaration

public static List<String> getAllLocalHostNames() 

Method Source Code

//package com.java2s;
/*//from   ww w . j  a v  a  2 s  .  c om
 *  This file is part of the Heritrix web crawler (crawler.archive.org).
 *
 *  Licensed to the Internet Archive (IA) by one or more individual 
 *  contributors. 
 *
 *  The IA 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.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;

import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

public class Main {
    /**
     * @return All known local names for this host or null if none found.
     */
    public static List<String> getAllLocalHostNames() {
        List<String> localNames = new ArrayList<String>();
        Enumeration<NetworkInterface> e = null;
        try {
            e = NetworkInterface.getNetworkInterfaces();
        } catch (SocketException exception) {
            throw new RuntimeException(exception);
        }
        for (; e.hasMoreElements();) {
            for (Enumeration<InetAddress> ee = e.nextElement()
                    .getInetAddresses(); ee.hasMoreElements();) {
                InetAddress ia = ee.nextElement();
                if (ia != null) {
                    if (ia.getHostName() != null) {
                        localNames.add(ia.getCanonicalHostName());
                    }
                    if (ia.getHostAddress() != null) {
                        localNames.add(ia.getHostAddress());
                    }
                }
            }
        }
        final String localhost = "localhost";
        if (!localNames.contains(localhost)) {
            localNames.add(localhost);
        }
        final String localhostLocaldomain = "localhost.localdomain";
        if (!localNames.contains(localhostLocaldomain)) {
            localNames.add(localhostLocaldomain);
        }
        return localNames;
    }
}

Related

  1. createLocalHostID(int size)
  2. getCanonicalLocalHostName()
  3. getCanonicalLocalHostName()
  4. getLocalHost()
  5. getLocalHost()