集册 Java实例教程 获取所有本地主机名

获取所有本地主机名

欢马劈雪     最近更新时间:2020-01-02 10:19:05

587
提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
获取所有本地主机名

/* InetAddressUtil

 *

 * Created on Nov 19, 2004

 *

 * Copyright (C) 2004 Internet Archive.

 *

 * This file is part of the Heritrix web crawler (crawler.archive.org).

 *

 * Heritrix is free software; you can redistribute it and/or modify

 * it under the terms of the GNU Lesser Public License as published by

 * the Free Software Foundation; either version 2.1 of the License, or

 * any later version.

 *

 * Heritrix is distributed in the hope that it will be useful,

 * but WITHOUT ANY WARRANTY; without even the implied warranty of

 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the

 * GNU Lesser Public License for more details.

 *

 * You should have received a copy of the GNU Lesser Public License

 * along with Heritrix; if not, write to the Free Software

 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

 */

//package com.nowjava;

import java.net.InetAddress;
/**来自 
 nowjava.com**/

import java.net.NetworkInterface;

import java.net.SocketException;


import java.util.ArrayList;

import java.util.Enumeration;

import java.util.List;


public class Main {

    public static void main(String[] argv) throws Exception {

        System.out.println(getAllLocalHostNames());

    }

    /*
     from nowjava 
    */

    /**

     * @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());

                    }

                }

            }

        
展开阅读全文