集册 Java实例教程 选择默认网络接口

选择默认网络接口

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

544
提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
选择默认网络接口


//package com.nowjava;

import java.net.InetAddress;

import java.net.NetworkInterface;/** 时   代     Java  公  众  号 - nowjava.com 提 供 **/

import java.util.Enumeration;


public class Main {

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

        System.out.println(getDefaultNetworkInterface());

    }


    /**

     * Selects the default network interface

     * @return network interface

     */

    public static NetworkInterface getDefaultNetworkInterface() {

        try {
        /** from 
        nowjava - 时代Java**/

            Enumeration<NetworkInterface> networks = NetworkInterface

                    .getNetworkInterfaces();

            while (networks.hasMoreElements()) {

                NetworkInterface ni = networks.nextElement();

                Enumeration<InetAddress> addresses = ni.getInetAddresses();

                boolean hasAddress = false;

                while (addresses.hasMoreElements()) {

                    InetAddress ia = addresses.nextElement();

                    if (!(ia.isAnyLocalAddress() || ia.isLinkLocalAddress()

                            || ia.isLoopbackAddress()

                            || ia.isSiteLocalAddress() || ni

                                .isPointToPoint())) {

                      
展开阅读全文