集册 Java实例教程 返回最有可能是外部地址的地址。

返回最有可能是外部地址的地址。

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

511
提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
返回最有可能是外部地址的地址。

/*

 *           GNU GENERAL PUBLIC LICENSE

 *              Version 2, June 1991

 * 

 *          ADDITIONAL REQUIREMENT

 *          

 * 1. If PeerfactSim.KOM is used for the evaluation in research publications, 

 * the following should be referenced: 

 * 

 * @techreport{   PWLS07,

 *    author = {Konstantin Pussep and Matthias Weinert and Nicolas Liebau and Ralf Steinmetz},

 *    title = {Flexible Framework for NAT Traversal in Peer-to-Peer Applications},

 *    month = {Nov},

 *    year = {2007},

 *    institution = {KOM - Multimedia Communications Lab, Technische Universit{\"a}t Darmstadt},

 *    address = {Merckstra{\ss}e 25, 64283 Darmstadt, Germany},

 *    number = {KOM-TR-2007-06},

 * }

 */

//package com.nowjava;//来 自 n o w j a v a . c o m

import java.net.InetAddress;


import java.net.NetworkInterface;

import java.net.SocketException;

import java.util.ArrayList;

import java.util.Collection;

import java.util.Enumeration;

import java.util.Iterator;


public class Main {

    public static void main(String[] argv) throws Exception {
    /*
     from nowjava - 时  代  Java 
    */

        System.out.println(getMostProbableExternalAddress());

    }


    /**

     * Returns the address which is most likely the external address. The result does not have

     * to be valid in the external network, since this method does not check for NAT-environments

     * etc.

     * 

     * @param addresses list of addresses

     * @return the address which is most probably the external address

     */

    public static InetAddress getMostProbableExternalAddress() {

        // get network interfaces

        Collection<NetworkInterface> activeIfs = getNetworkInterfaces();


        // get non-internal addresses

        ArrayList<InetAddress> localAddr = new ArrayList<InetAddress>();

        ArrayList<InetAddress> nonLocalAddr = new ArrayList<InetAddress>();

        for (NetworkInterface ni : activeIfs) {

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

            while (addresses.hasMoreElements()) {

                InetAddress addr = addresses.nextElement();

                if (hasLocalScope(addr))

                    localAddr.add(addr);

                else

                    nonLocalAddr.add(addr);

            }

        }


        // have nonlocal addresses? then return the "best"

        if (!nonLocalAddr.isEmpty()) {

            String removeAddrPrefixes[] = { "5.", "10.", "192." };

            for (String s : removeAddrPrefixes) {

                InetAddress last = nonLocalAddr.get(0);

                if (nonLocalAddr.size() == 1)

                    return last;

                removeAddressesWith(nonLocalAddr, s);

                if (nonLocalAddr.size() == 0)

                    return last;

                else if (nonLocalAddr.size() == 1)

                    return nonLocalAddr.get(0);

            }


            // we tried to get the right one, but more than one are left.. return first entree

            return nonLocalAddr.get(0);

        }


        // we dont want to return (link-)local addresses, throw exception

        throw new IllegalStateException("No external address found!");

    }


    /**

     * Returns all network interfaces of this host.

     * @return all network interfaces of this host

     */

    public static Collection<NetworkInterface> getNetworkInterfaces() {

        // get network interfaces

        ArrayList<NetworkInterface> result = new ArrayList<NetworkInterface>();

        Enumeration<NetworkInterface> ifs = null;

        try {

            ifs = NetworkInterface.getNetworkInterfaces();

        } catch (SocketException e1) {

            throw new IllegalStateException(

                    "Could not enumerate network interfaces!");

        }

        while (ifs.hasMoreElements()) {

            result.add(ifs.nextElement());

        }

        return result;

    }


    
展开阅读全文