Java Local Address Check isLocalAddress(String address)

Here you can find the source of isLocalAddress(String address)

Description

Figure out if the address is local.

License

Open Source License

Parameter

Parameter Description
address Address to analyze.

Exception

Parameter Description
SocketException if there was a problem talking to the network.
UnknownHostException if the address given can't be resolved.

Return

true if the address is local.

Declaration

public static boolean isLocalAddress(String address) throws SocketException, UnknownHostException 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Set;

public class Main {
    /**/* www.  j av  a 2  s. c  o  m*/
     * Figure out if the address is local.
     *
     * @param address Address to analyze.
     *
     * @return {@code true} if the address is local.
     * @throws SocketException if there was a problem talking to the network.
     * @throws UnknownHostException if the address given can't be resolved.
     */
    public static boolean isLocalAddress(String address) throws SocketException, UnknownHostException {

        InetAddress targetAddress = InetAddress.getByName(address);

        // Since the network configuration is dynamic, we'd rather collect
        // the addresses right now

        return getLocalAddresses().contains(targetAddress);
    }

    /**
     * Get a set of local host addresses.
     *
     * @return Set of local host addresses.
     * @throws SocketException if there was a problem talking to the network.
     */
    public static Set<InetAddress> getLocalAddresses() throws SocketException {

        Set<InetAddress> result = new HashSet<InetAddress>();

        for (Enumeration<NetworkInterface> e = NetworkInterface.getNetworkInterfaces(); e.hasMoreElements();) {

            NetworkInterface ni = e.nextElement();

            // complain(LOG_ALERT, getLogChannel(), "Interface: " +
            // ni.getDisplayName());

            for (Enumeration<InetAddress> e2 = ni.getInetAddresses(); e2.hasMoreElements();) {

                InetAddress niAddress = e2.nextElement();

                // complain(LOG_ALERT, getLogChannel(), "Address: " +
                // niAddress);

                result.add(niAddress);
            }
        }

        return result;
    }
}

Related

  1. isLocal(String brokerAddress)
  2. isLocalAddress(final String addr)
  3. isLocalAddress(final String address)
  4. isLocalAddress(String address)
  5. isLocalAddress(String address)
  6. isLocalAddress(String host)
  7. isLocalOrLoopback(String address)
  8. isLoopbackAddress(String address)
  9. isMyAddress(String host)