Example usage for java.net NetworkInterface getByInetAddress

List of usage examples for java.net NetworkInterface getByInetAddress

Introduction

In this page you can find the example usage for java.net NetworkInterface getByInetAddress.

Prototype

public static NetworkInterface getByInetAddress(InetAddress addr) throws SocketException 

Source Link

Document

Convenience method to search for a network interface that has the specified Internet Protocol (IP) address bound to it.

Usage

From source file:com.cloud.utils.net.NetUtils.java

public static String getMacAddress(final InetAddress address) {
    final StringBuffer sb = new StringBuffer();
    final Formatter formatter = new Formatter(sb);
    try {/* w ww  .j a v  a2  s .  c  om*/
        final NetworkInterface ni = NetworkInterface.getByInetAddress(address);
        final byte[] mac = ni.getHardwareAddress();

        for (int i = 0; i < mac.length; i++) {
            formatter.format("%02X%s", mac[i], i < mac.length - 1 ? ":" : "");
        }
    } catch (final SocketException e) {
        s_logger.error("SocketException when trying to retrieve MAC address", e);
    } finally {
        formatter.close();
    }
    return sb.toString();
}

From source file:com.cloud.utils.net.NetUtils.java

public static long getMacAddressAsLong(final InetAddress address) {
    long macAddressAsLong = 0;
    try {/*from www . ja va 2  s . com*/
        final NetworkInterface ni = NetworkInterface.getByInetAddress(address);
        final byte[] mac = ni.getHardwareAddress();

        for (int i = 0; i < mac.length; i++) {
            macAddressAsLong |= (long) (mac[i] & 0xff) << (mac.length - i - 1) * 8;
        }

    } catch (final SocketException e) {
        s_logger.error("SocketException when trying to retrieve MAC address", e);
    }

    return macAddressAsLong;
}

From source file:com.jagornet.dhcpv6.server.DhcpV6Server.java

/**
 * Gets the IPv6 network interfaces for the supplied interface names.
 * //  w  w  w. j  a v a2 s . c  o m
 * @param ifnames the interface names to locate NetworkInterfaces by
 * 
 * @return the list of NetworkInterfaces that are up, support multicast,
 * and have at least one IPv6 address configured
 * 
 * @throws SocketException the socket exception
 */
private List<NetworkInterface> getIPv6NetIfs(String[] ifnames) throws SocketException {
    List<NetworkInterface> netIfs = new ArrayList<NetworkInterface>();
    for (String ifname : ifnames) {
        if (ifname.equals("*")) {
            return getAllIPv6NetIfs();
        }
        NetworkInterface netIf = NetworkInterface.getByName(ifname);
        if (netIf == null) {
            // if not found by name, see if the name is actually an address
            try {
                InetAddress ipaddr = InetAddress.getByName(ifname);
                netIf = NetworkInterface.getByInetAddress(ipaddr);
            } catch (UnknownHostException ex) {
                log.warn("Unknown interface: " + ifname + ": " + ex);
            }
        }
        if (netIf != null) {
            if (netIf.isUp()) {
                // for multicast, the loopback interface is excluded
                if (netIf.supportsMulticast() && !netIf.isLoopback()) {
                    boolean isV6 = false;
                    List<InterfaceAddress> ifAddrs = netIf.getInterfaceAddresses();
                    for (InterfaceAddress ifAddr : ifAddrs) {
                        if (ifAddr.getAddress() instanceof Inet6Address) {
                            netIfs.add(netIf);
                            isV6 = true;
                            break;
                        }
                    }
                    if (!isV6) {
                        System.err.println("Interface is not configured for IPv6: " + netIf.getDisplayName());
                        return null;
                    }
                } else {
                    System.err.println("Interface does not support multicast: " + netIf.getDisplayName());
                    return null;
                }
            } else {
                System.err.println("Interface is not up: " + netIf.getDisplayName());
                return null;
            }
        } else {
            System.err.println("Interface not found or inactive: " + ifname);
            return null;
        }
    }
    return netIfs;
}

From source file:com.groupon.odo.bmp.ProxyServer.java

public void setLocalHost(InetAddress localHost) throws SocketException {
    if (localHost.isAnyLocalAddress() || localHost.isLoopbackAddress()
            || NetworkInterface.getByInetAddress(localHost) != null) {
        this.localHost = localHost;
    } else {/*from   ww  w  .ja va2  s. com*/
        throw new IllegalArgumentException("Must be address of a local adapter");
    }
}

From source file:nz.co.fortytwo.signalk.util.Util.java

public static boolean sameNetwork(String localAddress, String remoteAddress) throws Exception {
    InetAddress addr = InetAddress.getByName(localAddress);
    NetworkInterface networkInterface = NetworkInterface.getByInetAddress(addr);
    short netmask = -1;
    for (InterfaceAddress address : networkInterface.getInterfaceAddresses()) {
        if (address.getAddress().equals(addr)) {
            netmask = address.getNetworkPrefixLength();
        }//from  www .  j  a v a 2s .  c o m
    }
    byte[] a1 = InetAddress.getByName(localAddress).getAddress();
    byte[] a2 = InetAddress.getByName(remoteAddress).getAddress();
    byte[] m = InetAddress.getByName(normalizeFromCIDR(netmask)).getAddress();

    for (int i = 0; i < a1.length; i++)
        if ((a1[i] & m[i]) != (a2[i] & m[i]))
            return false;

    return true;

}

From source file:org.apache.hadoop.hdfs.DFSClient.java

private static boolean isLocalAddress(InetSocketAddress targetAddr) {
    InetAddress addr = targetAddr.getAddress();
    if (localIpAddresses.contains(addr.getHostAddress())) {
        if (LOG.isTraceEnabled()) {
            LOG.trace("Address " + targetAddr + " is local");
        }// www.j av a2s . c om
        return true;
    }

    // Check if the address is any local or loop back
    boolean local = addr.isAnyLocalAddress() || addr.isLoopbackAddress();

    // Check if the address is defined on any interface
    if (!local) {
        try {
            local = NetworkInterface.getByInetAddress(addr) != null;
        } catch (SocketException e) {
            local = false;
        }
    }
    if (LOG.isTraceEnabled()) {
        LOG.trace("Address " + targetAddr + " is local");
    }
    if (local == true) {
        localIpAddresses.add(addr.getHostAddress());
    }
    return local;
}

From source file:org.apache.hadoop.hdfs.qjournal.server.JournalNodeJournalSyncer.java

/**
 * Checks if the address is local./* w  w w.  j a v  a2  s.  co m*/
 */
private boolean isLocalIpAddress(InetAddress addr) {
    if (addr.isAnyLocalAddress() || addr.isLoopbackAddress())
        return true;
    try {
        return NetworkInterface.getByInetAddress(addr) != null;
    } catch (SocketException e) {
        return false;
    }
}

From source file:com.vuze.plugin.azVPN_PIA.Checker.java

private int handleBound(InetAddress bindIP, StringBuilder sReply) {
    int newStatusID = STATUS_ID_OK;

    String s;/*  ww  w . j a v a 2 s  .c om*/
    boolean isGoodExistingBind = matchesVPNIP(bindIP);
    if (isGoodExistingBind) {
        String niName = "Unknown Interface";
        try {
            NetworkInterface networkInterface = NetworkInterface.getByInetAddress(bindIP);
            niName = networkInterface.getName() + " (" + networkInterface.getDisplayName() + ")";
        } catch (Throwable e) {
        }
        addReply(sReply, CHAR_GOOD, "pia.bound.good", new String[] { "" + bindIP, niName });
        vpnIP = bindIP;
    } else {
        addReply(sReply, CHAR_BAD, "pia.bound.bad", new String[] { "" + bindIP });
        newStatusID = STATUS_ID_BAD;
    }

    try {
        // Check if default routing goes through 10.*, by connecting to address
        // via socket.  Address doesn't need to be reachable, just routable.
        // This works on Windows (in some cases), but on Mac returns a wildcard 
        // address
        DatagramSocket socket = new DatagramSocket();
        socket.connect(testSocketAddress, 0);
        InetAddress localAddress = socket.getLocalAddress();
        socket.close();

        if (!localAddress.isAnyLocalAddress()) {
            NetworkInterface networkInterface = NetworkInterface.getByInetAddress(localAddress);

            s = texts.getLocalisedMessageText("pia.nonvuze.probable.route", new String[] { "" + localAddress,
                    networkInterface.getName() + " (" + networkInterface.getDisplayName() + ")" });
            char replyChar = ' ';

            if ((localAddress instanceof Inet4Address) && matchesVPNIP(localAddress)) {

                if (localAddress.equals(bindIP)) {
                    replyChar = isGoodExistingBind ? CHAR_GOOD : CHAR_WARN;
                    s += " " + texts.getLocalisedMessageText("pia.same.as.vuze");
                } else {
                    // Vuze is bound, default routing goes somewhere else
                    // This is ok, since Vuze will not accept incoming from "somewhere else"
                    // We'll warn, but not update the status id

                    replyChar = CHAR_WARN;
                    s += " " + texts.getLocalisedMessageText("pia.not.same");

                    if (isGoodExistingBind) {
                        s += " " + texts.getLocalisedMessageText("default.routing.not.vpn.network.splitting");
                    }
                }

                addLiteralReply(sReply, replyChar + " " + s);

                if (!isGoodExistingBind && rebindNetworkInterface) {
                    rebindNetworkInterface(networkInterface, localAddress, sReply);
                    // Should we redo test?
                }

            } else {
                // Vuze is bound, default routing goes to somewhere else.
                // Probably network splitting
                replyChar = isGoodExistingBind ? CHAR_WARN : CHAR_BAD;
                if (isGoodExistingBind) {
                    s += " " + texts.getLocalisedMessageText("default.routing.not.vpn.network.splitting");
                }
                addLiteralReply(sReply, replyChar + " " + s);
            }
        }
    } catch (Throwable t) {
        t.printStackTrace();
    }
    return newStatusID;
}

From source file:org.apache.hadoop.net.NetUtils.java

/**
 * Checks if {@code host} is a local host name and return {@link InetAddress}
 * corresponding to that address./*www.ja va 2  s .co m*/
 * 
 * @param host the specified host
 * @return a valid local {@link InetAddress} or null
 * @throws SocketException if an I/O error occurs
 */
public static InetAddress getLocalInetAddress(String host) throws SocketException {
    if (host == null) {
        return null;
    }
    InetAddress addr = null;
    try {
        addr = InetAddress.getByName(host);
        if (NetworkInterface.getByInetAddress(addr) == null) {
            addr = null; // Not a local address
        }
    } catch (UnknownHostException ignore) {
    }
    return addr;
}

From source file:com.buaa.cfs.utils.NetUtils.java

/**
 * Checks if {@code host} is a local host name and return {@link InetAddress} corresponding to that address.
 *
 * @param host the specified host/*from  www .  java 2s  .c o  m*/
 *
 * @return a valid local {@link InetAddress} or null
 *
 * @throws SocketException if an I/O error occurs
 */
public static InetAddress getLocalInetAddress(String host) throws SocketException {
    if (host == null) {
        return null;
    }
    InetAddress addr = null;
    try {
        addr = SecurityUtil.getByName(host);
        if (NetworkInterface.getByInetAddress(addr) == null) {
            addr = null; // Not a local address
        }
    } catch (UnknownHostException ignore) {
    }
    return addr;
}