Example usage for java.net NetworkInterface isUp

List of usage examples for java.net NetworkInterface isUp

Introduction

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

Prototype


public boolean isUp() throws SocketException 

Source Link

Document

Returns whether a network interface is up and running.

Usage

From source file:org.opendaylight.lispflowmapping.implementation.lisp.MapServer.java

private static InetAddress getLocalAddress() {
    try {/*from  w ww.j  ava  2s. co m*/
        Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
        while (interfaces.hasMoreElements()) {
            NetworkInterface current = interfaces.nextElement();
            LOG.debug("Interface " + current.toString());
            if (!current.isUp() || current.isLoopback() || current.isVirtual()) {
                continue;
            }
            Enumeration<InetAddress> addresses = current.getInetAddresses();
            while (addresses.hasMoreElements()) {
                InetAddress current_addr = addresses.nextElement();
                // Skip loopback and link local addresses
                if (current_addr.isLoopbackAddress() || current_addr.isLinkLocalAddress()) {
                    continue;
                }
                LOG.debug(current_addr.getHostAddress());
                return current_addr;
            }
        }
    } catch (SocketException se) {
        LOG.debug("Caught socket exceptio", se);
    }
    return null;
}

From source file:com.jiangyifen.ec2.globaldata.license.LicenseManager.java

/**
 * "xx-xx-xx-xx-xx-xx"??MAC?/*from ww w . j  a  v a2 s .c o  m*/
 * 
 * @return
 * @throws Exception
 */
private static List<String> getMacAddressList() {
    List<String> macAddressList = new ArrayList<String>();
    try {
        Enumeration<NetworkInterface> ni = NetworkInterface.getNetworkInterfaces();

        while (ni.hasMoreElements()) {
            NetworkInterface netI = ni.nextElement();

            byte[] bytes = netI.getHardwareAddress();
            if (netI.isUp() && netI != null && bytes != null && bytes.length == 6) {
                StringBuffer sb = new StringBuffer();
                for (byte b : bytes) {
                    // 11110000????4?
                    sb.append(Integer.toHexString((b & 240) >> 4));
                    // 00001111????4?
                    sb.append(Integer.toHexString(b & 15));
                    sb.append("-");
                }
                sb.deleteCharAt(sb.length() - 1);
                macAddressList.add(sb.toString().toLowerCase());
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    return macAddressList;
}

From source file:org.cc86.MMC.client.Main.java

public static String serverDiscovery() {
    String res = "0.0.0.0";
    DatagramSocket c;// ww  w.  ja v  a 2 s  .com
    // Find the server using UDP broadcast
    try {
        //Open a random port to send the package
        c = new DatagramSocket();
        c.setBroadcast(true);

        byte[] sendData = "DISCOVER_MMC_REQUEST".getBytes();

        //Try the 255.255.255.255 first
        try {
            DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length,
                    InetAddress.getByName("255.255.255.255"), 0xCC86);
            c.send(sendPacket);
            l.info("Request packet sent to: 255.255.255.255 (DEFAULT)");
        } catch (Exception e) {
        }

        // Broadcast the message over all the network interfaces
        Enumeration interfaces = NetworkInterface.getNetworkInterfaces();
        while (interfaces.hasMoreElements()) {
            NetworkInterface networkInterface = (NetworkInterface) interfaces.nextElement();

            if (networkInterface.isLoopback() || !networkInterface.isUp()) {
                continue; // Don't want to broadcast to the loopback interface
            }

            for (InterfaceAddress interfaceAddress : networkInterface.getInterfaceAddresses()) {
                InetAddress broadcast = interfaceAddress.getBroadcast();
                if (broadcast == null) {
                    continue;
                }

                // Send the broadcast package!
                try {
                    DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, broadcast, 8888);
                    c.send(sendPacket);
                } catch (Exception e) {
                }

                l.info("Request packet sent to: " + broadcast.getHostAddress() + "; Interface: "
                        + networkInterface.getDisplayName());
            }
        }

        l.info("Done looping over all network interfaces. Now waiting for a reply!");

        //Wait for a response
        byte[] recvBuf = new byte[15000];
        DatagramPacket receivePacket = new DatagramPacket(recvBuf, recvBuf.length);
        c.receive(receivePacket);

        //We have a response
        l.info("Broadcast response from server: " + receivePacket.getAddress().getHostAddress());

        //Check if the message is correct
        String message = new String(receivePacket.getData()).trim();
        if (message.equals("DISCOVER_MMC_RESPONSE")) {
            //DO SOMETHING WITH THE SERVER'S IP (for example, store it in your controller)
            res = (receivePacket.getAddress() + "").substring(1);
        }

        //Close the port!
        c.close();
    } catch (IOException ex) {

    }
    return res;
}

From source file:Main.java

private static void displayInterfaceInformation(NetworkInterface netint) throws SocketException {
    System.out.printf("Display name: %s%n", netint.getDisplayName());
    System.out.printf("Name: %s%n", netint.getName());
    Enumeration<InetAddress> inetAddresses = netint.getInetAddresses();
    for (InetAddress inetAddress : Collections.list(inetAddresses)) {
        System.out.printf("InetAddress: %s%n", inetAddress);
    }/*from  w w w.j a va  2s.  c om*/

    System.out.printf("Parent: %s%n", netint.getParent());
    System.out.printf("Up? %s%n", netint.isUp());
    System.out.printf("Loopback? %s%n", netint.isLoopback());
    System.out.printf("PointToPoint? %s%n", netint.isPointToPoint());
    System.out.printf("Supports multicast? %s%n", netint.isVirtual());
    System.out.printf("Virtual? %s%n", netint.isVirtual());
    System.out.printf("Hardware address: %s%n", Arrays.toString(netint.getHardwareAddress()));
    System.out.printf("MTU: %s%n", netint.getMTU());

    List<InterfaceAddress> interfaceAddresses = netint.getInterfaceAddresses();
    for (InterfaceAddress addr : interfaceAddresses) {
        System.out.printf("InterfaceAddress: %s%n", addr.getAddress());
    }
    System.out.printf("%n");
    Enumeration<NetworkInterface> subInterfaces = netint.getSubInterfaces();
    for (NetworkInterface networkInterface : Collections.list(subInterfaces)) {
        System.out.printf("%nSubInterface%n");
        displayInterfaceInformation(networkInterface);
    }
    System.out.printf("%n");
}

From source file:net.grinder.util.NetworkUtils.java

static InetAddress getFirstNonLoopbackAddress(boolean preferIpv4, boolean preferIPv6) throws SocketException {
    Enumeration<?> en = getNetworkInterfaces();
    while (en.hasMoreElements()) {
        NetworkInterface i = (NetworkInterface) en.nextElement();
        if (!i.isUp()) {
            continue;
        }/*from  w  w  w  .ja v a  2s .c  o m*/
        for (Enumeration<?> en2 = i.getInetAddresses(); en2.hasMoreElements();) {
            InetAddress addr = (InetAddress) en2.nextElement();
            if (!addr.isLoopbackAddress()) {
                if (addr instanceof Inet4Address) {
                    if (preferIPv6) {
                        continue;
                    }
                    return addr;
                }
                if (addr instanceof Inet6Address) {
                    if (preferIpv4) {
                        continue;
                    }
                    return addr;
                }
            }
        }
    }
    return null;
}

From source file:net.grinder.util.NetworkUtils.java

/**
 * Check if the current machine support IP6
 *
 * @return true if the IP6 is supported.
 *///from w w w. j  a  va  2s  .  c o m
public static boolean isIP6Supported() {
    final Enumeration<NetworkInterface> networkInterfaces;
    try {
        networkInterfaces = getNetworkInterfaces();
        while (networkInterfaces.hasMoreElements()) {
            final NetworkInterface networkInterface = networkInterfaces.nextElement();
            if (networkInterface.isUp() && !networkInterface.isLoopback()
                    && !networkInterface.isPointToPoint()) {
                final Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses();
                while (inetAddresses.hasMoreElements()) {
                    final InetAddress inetAddress = inetAddresses.nextElement();
                    if (inetAddress instanceof Inet6Address) {
                        return true;
                    }
                }
            }
        }
    } catch (SocketException e) {
        LOGGER.error("Error while resolving non look back local addresses.", e);
    }
    return false;

}

From source file:net.grinder.util.NetworkUtils.java

private static List<InetAddress> getAllLocalNonLoopbackAddresses(boolean onlyIPv4) {
    List<InetAddress> addresses = new ArrayList<InetAddress>();
    final Enumeration<NetworkInterface> networkInterfaces;
    try {//from  w w  w  .ja  v a  2 s. com
        networkInterfaces = getNetworkInterfaces();
        while (networkInterfaces.hasMoreElements()) {

            final NetworkInterface networkInterface = networkInterfaces.nextElement();
            if (networkInterface.isUp()) {
                final Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses();
                while (inetAddresses.hasMoreElements()) {
                    final InetAddress inetAddress = inetAddresses.nextElement();
                    if (onlyIPv4 && inetAddress instanceof Inet6Address) {
                        continue;
                    }
                    if (!inetAddress.isLoopbackAddress()) {
                        addresses.add(inetAddress);
                    }
                }
            }
        }
    } catch (SocketException e) {
        LOGGER.error("Error while resolving non look back local addresses.", e);
    }
    return addresses;
}

From source file:com.git.original.common.utils.IPUtils.java

/**
 * ?IP?/* ww w .  j av  a 2s  . c  o m*/
 * <p>
 * :<br/>
 * 1. 192.xxx.xxx.xxx<br>
 * 2. 172.xxx.xxx.xxx<br>
 * 3. 10.xxx.xxx.xxx<br>
 * other<br>
 * 
 * @return ipv4?
 * @throws SocketException
 */
private static synchronized int doGetLocalIp() throws SocketException {
    if (localIp != 0) {
        return localIp;
    }

    Integer ipStartWith10 = null;
    Integer ipStartWith172 = null;
    Integer other = null;

    /*
     * ?IP?
     */
    Enumeration<NetworkInterface> interfaceEnum = NetworkInterface.getNetworkInterfaces();
    while (interfaceEnum.hasMoreElements()) {
        NetworkInterface netInterface = interfaceEnum.nextElement();
        if (!netInterface.isUp()) {
            continue;
        }

        Enumeration<InetAddress> addrEnum = netInterface.getInetAddresses();
        while (addrEnum.hasMoreElements()) {
            InetAddress addr = addrEnum.nextElement();
            String hostAddr = addr.getHostAddress();

            if (hostAddr.startsWith("192.")) {
                localIp = ByteUtils.toInt(addr.getAddress());
                return localIp;
            } else if (ipStartWith172 == null && hostAddr.startsWith("172.")) {
                ipStartWith172 = ByteUtils.toInt(addr.getAddress());
            } else if (ipStartWith10 == null && hostAddr.startsWith("10.")) {
                ipStartWith10 = ByteUtils.toInt(addr.getAddress());
            } else if (other == null && (addr instanceof Inet4Address)) {
                other = ByteUtils.toInt(addr.getAddress());
            }
        }
    }

    if (ipStartWith172 != null) {
        localIp = ipStartWith172;
        return localIp;
    } else if (ipStartWith10 != null) {
        localIp = ipStartWith10;
        return localIp;
    } else if (other != null) {
        localIp = other;
        return localIp;
    }

    throw new RuntimeException("can not get Local Server IPv4 Address");
}

From source file:com.qwazr.server.configuration.ServerConfiguration.java

/**
 * Manage that kind of pattern:/*  w w w  .  ja v a  2s  .c  o m*/
 * 192.168.0.0/16,172.168.0.0/16
 * 192.168.0.0/16
 * 10.3.12.12
 *
 * @param addressPattern a mask or an ip address
 * @param collect        a collection filled with the matching addresses
 * @throws SocketException
 */
private static void findMatchingAddress(final String addressPattern, final Collection<String> collect)
        throws SocketException {
    final String[] patterns = StringUtils.split(addressPattern, ",; ");
    if (patterns == null)
        return;
    for (String pattern : patterns) {
        if (pattern == null)
            continue;
        pattern = pattern.trim();
        if (!pattern.contains("/")) {
            collect.add(pattern);
            continue;
        }
        final SubnetUtils.SubnetInfo subnet = pattern.contains("/") ? new SubnetUtils(pattern).getInfo() : null;
        final Enumeration<NetworkInterface> enumInterfaces = NetworkInterface.getNetworkInterfaces();
        while (enumInterfaces != null && enumInterfaces.hasMoreElements()) {
            final NetworkInterface ifc = enumInterfaces.nextElement();
            if (!ifc.isUp())
                continue;
            final Enumeration<InetAddress> enumAddresses = ifc.getInetAddresses();
            while (enumAddresses != null && enumAddresses.hasMoreElements()) {
                final InetAddress inetAddress = enumAddresses.nextElement();
                if (!(inetAddress instanceof Inet4Address))
                    continue;
                final String address = inetAddress.getHostAddress();
                if (subnet != null && subnet.isInRange(address) || address.equals(pattern))
                    collect.add(address);
            }
        }
    }
}

From source file:com.entertailion.android.slideshow.utils.Utils.java

public static final InetAddress getLocalInetAddress() {
    InetAddress selectedInetAddress = null;
    try {/*from  www.  ja  va  2  s.  co m*/
        for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en
                .hasMoreElements();) {
            NetworkInterface intf = en.nextElement();
            if (intf.isUp()) {
                for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr
                        .hasMoreElements();) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress()) {
                        if (inetAddress instanceof Inet4Address) { // only
                            // want
                            // ipv4
                            // address
                            if (inetAddress.getHostAddress().toString().charAt(0) != '0') {
                                if (selectedInetAddress == null) {
                                    selectedInetAddress = inetAddress;
                                } else if (intf.getName().startsWith("eth")) { // prefer
                                    // wired
                                    // interface
                                    selectedInetAddress = inetAddress;
                                }
                            }
                        }
                    }
                }
            }
        }
        return selectedInetAddress;
    } catch (Throwable e) {
        Log.e(LOG_TAG, "Failed to get the IP address", e);
    }
    return null;
}