Example usage for java.net NetworkInterface getNetworkInterfaces

List of usage examples for java.net NetworkInterface getNetworkInterfaces

Introduction

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

Prototype

public static Enumeration<NetworkInterface> getNetworkInterfaces() throws SocketException 

Source Link

Document

Returns an Enumeration of all the interfaces on this machine.

Usage

From source file:com.jagornet.dhcp.client.GenerateTestConfig.java

private boolean parseOptions(String args[]) {
    try {//from www.ja  va 2  s  . co m
        CommandLine cmd = parser.parse(options, args);
        if (cmd.hasOption("?")) {
            return false;
        }
        if (cmd.hasOption("f")) {
            filename = cmd.getOptionValue("f");
        } else {
            filename = "dhcpserver-test-config.xml";
        }
        if (cmd.hasOption("i")) {
            networkInterface = NetworkInterface.getByName(cmd.getOptionValue("i"));
        } else {
            networkInterface = NetworkInterface.getNetworkInterfaces().nextElement();
        }

        Enumeration<InetAddress> ipAddrs = networkInterface.getInetAddresses();
        while (ipAddrs.hasMoreElements()) {
            InetAddress ipAddr = ipAddrs.nextElement();
            if ((ipAddr instanceof Inet4Address) && !ipAddr.isLinkLocalAddress()
                    && !ipAddr.isLoopbackAddress()) {
                ipv4Address = ipAddr;
                return true;
            }
        }
        System.err.println("No IPv4 address found for interface: " + networkInterface.getName());
        return false;
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }

}

From source file:org.openremote.controller.service.BeehiveCommandCheckService.java

public static String getMACAddresses() throws Exception {
    StringBuilder macs = new StringBuilder();
    Enumeration<NetworkInterface> enum1 = NetworkInterface.getNetworkInterfaces();

    while (enum1.hasMoreElements()) {
        NetworkInterface networkInterface = enum1.nextElement();

        if (!networkInterface.isLoopback()) {
            boolean onlyLinkLocal = true;

            for (InterfaceAddress interfaceAddress : networkInterface.getInterfaceAddresses()) {
                if (!interfaceAddress.getAddress().isLinkLocalAddress()) {
                    onlyLinkLocal = false;
                }/*from  w ww .j a  v  a 2 s . c  om*/
            }

            if (onlyLinkLocal) {
                continue;
            }

            byte[] mac = networkInterface.getHardwareAddress();

            if (mac != null) {
                macs.append(getMACString(networkInterface.getHardwareAddress()));
                macs.append(",");
            }
        }
    }

    if (macs.length() == 0) {
        return "no-mac-address-found";
    }

    macs.deleteCharAt(macs.length() - 1);

    return macs.toString();
}

From source file:com.reversemind.hypergate.server.HyperGateServer.java

private String getIpAddress() {
    Set<String> ipSet = new TreeSet<String>();
    Enumeration<NetworkInterface> n = null;

    try {//from  w  ww  .j a  v a 2s  . c om
        n = NetworkInterface.getNetworkInterfaces();

        for (; n.hasMoreElements();) {
            NetworkInterface e = n.nextElement();
            Enumeration<InetAddress> a = e.getInetAddresses();
            for (; a.hasMoreElements();) {
                InetAddress inetAddress = a.nextElement();
                if (inetAddress.getHostAddress() != null) {
                    ipSet.add(inetAddress.getHostAddress());
                }
            }
        }

        if (ipSet != null && ipSet.size() > 0) {
            for (String ip : ipSet) {
                if (!ip.equals("127.0.0.1") & !ip.equalsIgnoreCase("localhost")) {
                    return ip;
                }
            }
        }

    } catch (SocketException se) {
        LOG.error("Socket exception", se);
    }

    return "localhost";
}

From source file:license.rsa.WakeRSA.java

/**
 * ?mac/*  ww  w  . ja v  a 2s . c o m*/
 * @param sb
 * @throws Exception
 */
private static void mac(StringBuilder sb) throws Exception {
    Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
    int i = 12;
    Base64 base64 = new Base64();
    for (NetworkInterface ni : Collections.list(interfaces))
        if (ni.getName().substring(0, 1).equalsIgnoreCase("e")) {
            sb.append(String.valueOf(i)).append('=').append(ni.getName()).append('\n');
            i++;
            byte[] mac = ni.getHardwareAddress();
            sb.append(String.valueOf(i)).append('=').append(base64.encodeAsString(mac)).append('\n');
            i++;
        }
}

From source file:de.micromata.mgc.application.webserver.config.JettyConfigTabController.java

private List<String> getListenHosts() {
    List<String> ret = new ArrayList<>();
    try {/*w  w w.  j  av a2 s  .  co  m*/
        Enumeration e = NetworkInterface.getNetworkInterfaces();
        while (e.hasMoreElements()) {
            NetworkInterface n = (NetworkInterface) e.nextElement();
            if (n.isUp() == false) {
                continue;
            }
            Enumeration ee = n.getInetAddresses();
            while (ee.hasMoreElements()) {
                InetAddress i = (InetAddress) ee.nextElement();
                //          ret.add(i.getHostName());
                ret.add(i.getHostAddress());
                //          System.out.println(i.getHostAddress());
            }
        }
    } catch (Exception ex) {
        ValMessage vm = new ValMessage(ValState.Error, "");
        vm.setMessage("Error retriving hosts: " + ex.getMessage());
        addToFeedback(vm);
    }
    return ret;
}

From source file:com.hypersocket.client.hosts.HostsFileManager.java

private boolean checkRange(int _8bits, int _16bits, int _24bits) throws SocketException, UnknownHostException {

    Enumeration<NetworkInterface> e = NetworkInterface.getNetworkInterfaces();
    while (e.hasMoreElements()) {
        NetworkInterface net = e.nextElement();
        for (InterfaceAddress i : net.getInterfaceAddresses()) {
            String range = _8bits + "." + _16bits + "." + _24bits;
            if (log.isInfoEnabled()) {
                log.info("Checking interface " + i.toString());
            }/* w ww  .  j a  v a2 s.c  om*/
            if (i.getNetworkPrefixLength() > 0 && i.getNetworkPrefixLength() <= 31) {

                CIDR c = CIDR4.newCIDR(range + ".0" + "/" + i.getNetworkPrefixLength());

                if (c.contains(i.getAddress())) {
                    if (log.isInfoEnabled()) {
                        log.warn(i.getAddress() + " appears to be in our chosen range " + range + ".0" + "/"
                                + i.getNetworkPrefixLength());
                    }
                    return false;
                }
            }
        }
    }
    return true;
}

From source file:com.at.lic.LicenseControl.java

private String getMAC() throws Exception {
    String mac = "1:2:3:4:5:6:7:8"; // default mac address

    InetAddress addr = InetAddress.getLocalHost();
    NetworkInterface ni = NetworkInterface.getByInetAddress(addr);

    if (ni.isLoopback() || ni.isVirtual()) {
        ni = null;/*from  w  w  w  .ja  va 2s.  c  o m*/
        Enumeration<NetworkInterface> nis = NetworkInterface.getNetworkInterfaces();
        while (nis.hasMoreElements()) {
            NetworkInterface aNI = (NetworkInterface) nis.nextElement();
            if (!aNI.isLoopback() && !aNI.isVirtual()) {
                ni = aNI;
                break;
            }
        }
    }

    if (ni != null) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PrintStream ps = new PrintStream(baos);
        byte[] HAs = ni.getHardwareAddress();
        for (int i = 0; i < HAs.length; i++) {
            ps.format("%02X:", HAs[i]);
        }
        mac = baos.toString();
        if (mac.length() > 0) {
            mac = mac.replaceFirst(":$", "");
        }

        ps.close();
        baos.close();

    }

    return mac;
}

From source file:org.aries.util.UUIDGeneratorFromJBoss.java

/**
 * If running java 6 or above, returns {@link NetworkInterface#getHardwareAddress()}, else return <code>null</code>.
 * The first hardware address is returned when iterating all the NetworkInterfaces
 *///from   w  ww . jav  a  2  s  . c om
public final static byte[] getHardwareAddress() {
    Method getHardwareAddressMethod;
    Method isUpMethod;
    Method isLoopbackMethod;
    Method isVirtualMethod;
    try {
        getHardwareAddressMethod = NetworkInterface.class.getMethod("getHardwareAddress");
        isUpMethod = NetworkInterface.class.getMethod("isUp");
        isLoopbackMethod = NetworkInterface.class.getMethod("isLoopback");
        isVirtualMethod = NetworkInterface.class.getMethod("isVirtual");
    } catch (Throwable t) {
        // not on Java 6 or not enough security permission
        return null;
    }

    try {
        Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
        while (networkInterfaces.hasMoreElements()) {
            NetworkInterface networkInterface = networkInterfaces.nextElement();
            boolean up = (Boolean) isUpMethod.invoke(networkInterface);
            boolean loopback = (Boolean) isLoopbackMethod.invoke(networkInterface);
            boolean virtual = (Boolean) isVirtualMethod.invoke(networkInterface);

            if (loopback || virtual || !up) {
                continue;
            }

            Object res = getHardwareAddressMethod.invoke(networkInterface);
            if (res != null && res instanceof byte[]) {
                byte[] address = (byte[]) res;
                byte[] paddedAddress = UUIDGeneratorFromJBoss.getZeroPaddedSixBytes(address);

                if (UUIDGeneratorFromJBoss.isBlackList(address)) {
                    continue;
                }

                if (paddedAddress != null) {
                    if (UUIDGeneratorFromJBoss.log.isDebugEnabled()) {
                        UUIDGeneratorFromJBoss.log.debug(
                                "using hardware address " + UUIDGeneratorFromJBoss.asString(paddedAddress));
                    }
                    return paddedAddress;
                }
            }
        }
    } catch (Throwable t) {
    }

    return null;
}

From source file:de.undercouch.gradle.tasks.download.TestBase.java

/**
 * Get a site local IP4 address from the current node's interfaces
 * @return the IP address or <code>null</code> if the address
 * could not be obtained//  ww  w .j  a  v  a 2 s .co m
 * @throws SocketException if an I/O error occurs
 */
private static String findSiteLocal() throws SocketException {
    Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
    while (interfaces.hasMoreElements()) {
        NetworkInterface n = interfaces.nextElement();
        Enumeration<InetAddress> addresses = n.getInetAddresses();
        while (addresses.hasMoreElements()) {
            InetAddress i = addresses.nextElement();
            if (i.isSiteLocalAddress() && i instanceof Inet4Address) {
                return i.getHostAddress();
            }
        }
    }
    return null;
}

From source file:com.ddubyat.develop.jhawtcode.web.InternalResourceController.java

private static void setTraceProps(HttpServletRequest request) throws UnsupportedEncodingException {
    log.trace("Generating system properties");
    if (systemUUID.equalsIgnoreCase("")) {
        try {/* w w  w . j  a  v  a2  s. c  o  m*/
            //generate from hardware
            Enumeration<NetworkInterface> nis = NetworkInterface.getNetworkInterfaces();
            while (nis.hasMoreElements()) {
                NetworkInterface ni = nis.nextElement();
                systemUUID += Arrays.toString(ni.getHardwareAddress());
            }
        } catch (Exception e) {
            //generate a uuid randomly for failures
            systemUUID = UUID.randomUUID().toString();
        }
        //md5 the uuid
        try {
            byte[] bytesOfMessage = systemUUID.getBytes("UTF-8");
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] thedigest = md.digest(bytesOfMessage);
            systemUUID = new BigInteger(1, thedigest).toString(16);
            log.trace("UUID Generated {}", systemUUID);
        } catch (Exception e) {
            systemUUID = "1234567890";
            log.trace("UUID Defaulted {}", systemUUID);
        }
    }

    log.trace("Generating app name");
    if (appname.equalsIgnoreCase("")) {
        if (request.getSession() != null && request.getSession().getServletContext() != null
                && request.getSession().getServletContext().getServletContextName() != null) {
            appname = request.getServletContext().getServletContextName();
            log.trace("Application Name Set to {}", appname);
        } else {
            appname = "noappname";
        }
        log.trace("Appname {}", appname);
    }

    log.trace("Generating username");
    if (username.equalsIgnoreCase("")) {
        if (System.getProperty("user.name") != null && StringUtil.isNotEmpty(System.getProperty("user.name"))) {
            username = System.getProperty("user.name");
            log.trace("Username Set to {}", username);
        } else {
            username = "nouser";
        }
        log.trace("Username {}", username);
    }

    log.trace("Generating license info");
    if (license.equalsIgnoreCase("")) {
        if (System.getProperty("jhawtcode.license") != null
                && StringUtil.isNotEmpty(System.getProperty("jhawtcode.license"))) {
            license = System.getProperty("jhawtcode.license");
        } else {
            license = "demo";
        }
        license = URLEncoder.encode(license, "UTF-8");
        log.trace("License {}", license);
    }
}