Java examples for Network:Network Address
Returns true if the given address represents the local host.
/*/*from w ww. j a va2s . c o m*/ * 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.java2s; 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(); 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<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; } }