Java Local Host Get getLocalHostNames()

Here you can find the source of getLocalHostNames()

Description

get Local Host Names

License

Apache License

Declaration

public static String[] getLocalHostNames() 

Method Source Code

//package com.java2s;
/**//from   w w  w. ja va 2  s  .  co m
 * Copyright 2010 the original author or authors.
 *
 * Licensed 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.Enumeration;
import java.util.HashSet;
import java.util.Set;

public class Main {
    public static String[] getLocalHostNames() {
        final Set<String> hostNames = new HashSet<String>();
        // we add localhost to this set manually, because if the ip 127.0.0.1 is
        // configured with more than one name in the /etc/hosts, only the first
        // name
        // is returned
        hostNames.add("localhost");
        try {
            final Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
            for (final Enumeration<NetworkInterface> ifaces = networkInterfaces; ifaces.hasMoreElements();) {
                final NetworkInterface iface = ifaces.nextElement();
                InetAddress ia = null;
                for (final Enumeration<InetAddress> ips = iface.getInetAddresses(); ips.hasMoreElements();) {
                    ia = ips.nextElement();
                    hostNames.add(ia.getCanonicalHostName());
                    hostNames.add(ipToString(ia.getAddress()));
                }
            }
        } catch (final SocketException e) {
            throw new RuntimeException("unable to retrieve host names of localhost");
        }
        return hostNames.toArray(new String[hostNames.size()]);
    }

    private static String ipToString(final byte[] bytes) {
        final StringBuffer addrStr = new StringBuffer();
        for (int cnt = 0; cnt < bytes.length; cnt++) {
            final int uByte = bytes[cnt] < 0 ? bytes[cnt] + 256 : bytes[cnt];
            addrStr.append(uByte);
            if (cnt < 3)
                addrStr.append('.');
        }
        return addrStr.toString();
    }
}

Related

  1. getLocalHostName()
  2. getLocalHostName()
  3. getLocalHostName()
  4. getLocalHostName(boolean includeDomain)
  5. getLocalHostName(boolean useHostname)
  6. getLocalHosts()
  7. isLocalHost(String address)
  8. isLocalHost(String h1)
  9. isLocalhost(String host)