集册 Java实例教程 获取本地IP

获取本地IP

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

455
获取本地IP

/**

 * Copyright (c) 2009 - 2011 AppWork UG(haftungsbeschr?nkt) <e-mail@appwork.org>

 * 

 * This file is part of org.appwork.utils.net.httpconnection

 * 

 * This software is licensed under the Artistic License 2.0,

 * see the LICENSE file or http://www.opensource.org/licenses/artistic-license-2.0.php

 * for details

 */
 /**
 来 自 NowJava.com - 时代Java
 **/

import java.net.Inet4Address;

import java.net.InetAddress;

import java.net.NetworkInterface;

import java.util.ArrayList;

import java.util.Collections;

import java.util.Enumeration;

import java.util.LinkedHashSet;

import java.util.List;


public class Main{

    public static List<InetAddress> getLocalIPs() {

        return HTTPProxyUtils.getLocalIPs(false);

    }

    public static List<InetAddress> getLocalIPs(final boolean allowLoopback) {

        final LinkedHashSet<InetAddress> ipsLocal = new LinkedHashSet<InetAddress>();

        try {

            final Enumeration<NetworkInterface> nets = NetworkInterface

                    .getNetworkInterfaces();

            while (nets.hasMoreElements()) {
            /**
            NowJava.com - 时  代  Java 提供 
            **/

                /* find all network interfaces and their addresses */

                NetworkInterface cur = nets.nextElement();

                if (!cur.isUp()) {

                    continue;

                }

                if (cur.isLoopback() && allowLoopback == false) {

                    continue;

                }

                Enumeration<InetAddress> addrs = cur.getInetAddresses();

                InetAddress addr;

                while (addrs.hasMoreElements()) {

                    addr = addrs.nextElement();

                    if (addr == null) {

                        continue;

                    }

                    /* only show ipv4 addresses and non loopback */

                    if (!(addr instanceof Inet4Address)) {

                        continue;

                    }

                    ipsLocal.add(addr);

                }

                /* find all subinterfaces for each network interface, eg. eth0.1 */

                final Enumeration<NetworkInterface> nets2 = cur

                        .getSubInterfaces();

                while (nets2.hasMoreElements()) {

                    cur = nets2.nextElement();

                    if (!cur.isUp()) {

                        continue;

                    }

                    if (cur.isLoopback() && allowLoopback == false) {

                        continue;

                    }

                    addrs = cur.getInetAddresses();

                    while (addrs.hasMoreElements()) {

                        addr = addrs.nextElement();

                        if (addr == null) {

                            continue;

                
展开阅读全文