如果给定的地址表示本地主机,则返回true。
/* * 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}, * } *//* from 时 代 J a v a 公 众 号*/ //package com.nowjava; import java.net.InetAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.util.ArrayList; import java.util.Collection; import java.util.Enumeration; public class Main { /** * Returns true if the given address represents the local host. * @param addr address * @return true if the given address represents the local host */ public static boolean isLocalAddress(InetAddress addr) { // has local scope? if (hasLocalScope(addr)) return true; // compare to local addresses Collection<NetworkInterface> nis = getNetworkInterfaces(); for (NetworkInterface ni : nis) { Enumeration<InetAddress> addresses = ni.getInetAddresses(); /** from * 时代Java **/ while (addresses.hasMoreElements()) { if (addresses.nextElement().equals(addr)) return true; } } // found no equal address => its not local return false; } /** * Returns true when the given address is a local address. * @param addr address * @return true when the given address is a local address */ public static boolean hasLocalScope(InetAddress addr) { if (addr == null) throw new IllegalArgumentException("Must not be null!"); return (addr.isAnyLocalAddress() || addr.isLinkLocalAddress() || addr .isLoopbackAddress()); } /** * 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