Example usage for java.net NetworkInterface isVirtual

List of usage examples for java.net NetworkInterface isVirtual

Introduction

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

Prototype

public boolean isVirtual() 

Source Link

Document

Returns whether this interface is a virtual interface (also called subinterface).

Usage

From source file:net.ftb.util.OSUtils.java

/**
 * Grabs the mac address of computer and makes it 10 times longer
 * @return a byte array containing mac address
 *///from   ww  w  .jav a 2  s.  com
public static byte[] getMacAddress() {
    if (cachedMacAddress != null && cachedMacAddress.length >= 10) {
        return cachedMacAddress;
    }
    try {
        Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
        while (networkInterfaces.hasMoreElements()) {
            NetworkInterface network = networkInterfaces.nextElement();
            byte[] mac = network.getHardwareAddress();
            if (mac != null && mac.length > 0 && !network.isLoopback() && !network.isVirtual()
                    && !network.isPointToPoint() && network.getName().substring(0, 3) != "ham") {
                Logger.logDebug("Interface: " + network.getDisplayName() + " : " + network.getName());
                cachedMacAddress = new byte[mac.length * 10];
                for (int i = 0; i < cachedMacAddress.length; i++) {
                    cachedMacAddress[i] = mac[i - (Math.round(i / mac.length) * mac.length)];
                }
                return cachedMacAddress;
            }
        }
    } catch (SocketException e) {
        Logger.logWarn("Exception getting MAC address", e);
    }

    Logger.logWarn("Failed to get MAC address, using default logindata key");
    return new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 };
}

From source file:org.peercast.pecaport.NetworkDeviceManager.java

/**
 * ?(eth0, eth1..)??//  w  w  w. ja v  a 2 s .  c  o m
 */
public List<NetworkInterfaceInfo.Ethernet> getEthernetInterface() {
    List<NetworkInterfaceInfo.Ethernet> infos = new ArrayList<>();
    try {

        for (NetworkInterface ni : Collections.list(NetworkInterface.getNetworkInterfaces())) {
            if (!ni.isLoopback() && !ni.isVirtual() && ni.getName().matches("^eth\\d+$") && //
                    ni.getInetAddresses().hasMoreElements())
                infos.add(new NetworkInterfaceInfo.Ethernet(ni));
        }
    } catch (SocketException e) {
        Log.w(TAG, "getEthernetInterface()", e);
    }
    return infos;
}

From source file:terrastore.communication.NodeConfiguration.java

private String getPublishAddresses() throws Exception {
    Enumeration<NetworkInterface> nics = NetworkInterface.getNetworkInterfaces();
    StringBuilder result = new StringBuilder();
    while (nics != null && nics.hasMoreElements()) {
        NetworkInterface nic = nics.nextElement();
        if (nic.isUp() && !nic.isLoopback() && !nic.isVirtual() && nic.getInetAddresses().hasMoreElements()) {
            Enumeration<InetAddress> addresses = nic.getInetAddresses();
            while (addresses.hasMoreElements()) {
                if (result.length() > 0) {
                    result.append(",");
                }//from   w ww. j  a va  2 s  .  c  om
                result.append(addresses.nextElement().getHostAddress());
            }
        }
    }
    return result.toString();
}

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  .j  av a2 s .  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.openhab.binding.zway.internal.discovery.ZWayBridgeDiscoveryService.java

private void scan() {
    logger.debug("Starting scan for Z-Way Server");

    ValidateIPV4 validator = new ValidateIPV4();

    try {/*from   w  w  w. ja  v a 2  s .  c om*/
        Enumeration<NetworkInterface> enumNetworkInterface = NetworkInterface.getNetworkInterfaces();
        while (enumNetworkInterface.hasMoreElements()) {
            NetworkInterface networkInterface = enumNetworkInterface.nextElement();
            if (networkInterface.isUp() && !networkInterface.isVirtual() && !networkInterface.isLoopback()) {
                for (InterfaceAddress address : networkInterface.getInterfaceAddresses()) {
                    if (validator.isValidIPV4(address.getAddress().getHostAddress())) {
                        String ipAddress = address.getAddress().getHostAddress();
                        Short prefix = address.getNetworkPrefixLength();

                        logger.debug("Scan IP address for Z-Way Server: {}", ipAddress);

                        // Search on localhost first
                        scheduler.execute(new ZWayServerScan(ipAddress));

                        String subnet = ipAddress + "/" + prefix;
                        SubnetUtils utils = new SubnetUtils(subnet);
                        String[] addresses = utils.getInfo().getAllAddresses();

                        for (String addressInSubnet : addresses) {
                            scheduler.execute(new ZWayServerScan(addressInSubnet));
                        }
                    }
                }
            }
        }
    } catch (SocketException e) {
        logger.warn("Error occurred while searching Z-Way servers ({})", e.getMessage());
    }
}

From source file:org.openhab.binding.vera.internal.discovery.VeraBridgeDiscoveryService.java

private void scan() {
    logger.debug("Starting scan for Vera controller");

    ValidateIPV4 validator = new ValidateIPV4();

    try {//from www.j a  v  a  2s  . c  o m
        Enumeration<NetworkInterface> enumNetworkInterface = NetworkInterface.getNetworkInterfaces();
        while (enumNetworkInterface.hasMoreElements()) {
            NetworkInterface networkInterface = enumNetworkInterface.nextElement();
            if (networkInterface.isUp() && !networkInterface.isVirtual() && !networkInterface.isLoopback()) {
                for (InterfaceAddress address : networkInterface.getInterfaceAddresses()) {
                    if (validator.isValidIPV4(address.getAddress().getHostAddress())) {
                        String ipAddress = address.getAddress().getHostAddress();
                        Short prefix = address.getNetworkPrefixLength();

                        logger.debug("Scan IP address for Vera Controller: {}", ipAddress);

                        String subnet = ipAddress + "/" + prefix;
                        SubnetUtils utils = new SubnetUtils(subnet);
                        String[] addresses = utils.getInfo().getAllAddresses();

                        for (String addressInSubnet : addresses) {
                            scheduler.execute(new VeraControllerScan(addressInSubnet));
                        }
                    }
                }
            }
        }
    } catch (SocketException e) {
        logger.warn("Error occurred while searching Vera controller: ", e);
    }
}

From source file:com.almende.arum.EventPusher.java

private String getHostAddress() throws SocketException {
    Enumeration<NetworkInterface> e = NetworkInterface.getNetworkInterfaces();
    while (e.hasMoreElements()) {
        NetworkInterface n = (NetworkInterface) e.nextElement();
        if (!n.isLoopback() && n.isUp() && !n.isVirtual()) {

            Enumeration<InetAddress> ee = n.getInetAddresses();
            while (ee.hasMoreElements()) {
                InetAddress i = (InetAddress) ee.nextElement();
                if (i instanceof Inet4Address && !i.isLinkLocalAddress() && !i.isMulticastAddress()) {
                    return i.getHostAddress().trim();
                }//from w  w w  . j a  v a 2  s  .  c  om
            }
        }
    }
    return null;
}

From source file:edu.ucsb.eucalyptus.ic.WalrusReplyQueue.java

public void handle(ExceptionMessage muleMsg) {
    try {/*from  w  w w.j  a  va  2s  .co m*/
        Object requestMsg = muleMsg.getPayload();
        String requestString = requestMsg.toString();
        EucalyptusMessage msg = (EucalyptusMessage) BindingManager.getBinding("msgs_eucalyptus_ucsb_edu")
                .fromOM(requestString);
        Throwable ex = muleMsg.getException().getCause();
        EucalyptusMessage errMsg;

        String ipAddr = "127.0.0.1";
        List<NetworkInterface> ifaces = null;
        try {
            ifaces = Collections.list(NetworkInterface.getNetworkInterfaces());
        } catch (SocketException e1) {
        }

        for (NetworkInterface iface : ifaces) {
            try {
                if (!iface.isLoopback() && !iface.isVirtual() && iface.isUp()) {
                    for (InetAddress iaddr : Collections.list(iface.getInetAddresses())) {
                        if (!iaddr.isSiteLocalAddress() && !(iaddr instanceof Inet6Address)) {
                            ipAddr = iaddr.getHostAddress();
                            break;
                        }
                    }
                }
            } catch (SocketException e1) {
            }
        }

        if (ex instanceof NoSuchBucketException) {
            errMsg = new WalrusBucketErrorMessageType(((NoSuchBucketException) ex).getBucketName(),
                    "NoSuchBucket", "The specified bucket was not found", HttpStatus.SC_NOT_FOUND,
                    msg.getCorrelationId(), ipAddr);
            errMsg.setCorrelationId(msg.getCorrelationId());
        } else if (ex instanceof AccessDeniedException) {
            errMsg = new WalrusBucketErrorMessageType(((AccessDeniedException) ex).getBucketName(),
                    "AccessDenied", "No U", HttpStatus.SC_FORBIDDEN, msg.getCorrelationId(), ipAddr);
            errMsg.setCorrelationId(msg.getCorrelationId());
        } else if (ex instanceof NotAuthorizedException) {
            errMsg = new WalrusBucketErrorMessageType(((NotAuthorizedException) ex).getValue(), "Unauthorized",
                    "No U", HttpStatus.SC_UNAUTHORIZED, msg.getCorrelationId(), ipAddr);
            errMsg.setCorrelationId(msg.getCorrelationId());
        } else if (ex instanceof BucketAlreadyOwnedByYouException) {
            errMsg = new WalrusBucketErrorMessageType(((BucketAlreadyOwnedByYouException) ex).getBucketName(),
                    "BucketAlreadyOwnedByYou",
                    "Your previous request to create the named bucket succeeded and you already own it.",
                    HttpStatus.SC_CONFLICT, msg.getCorrelationId(), ipAddr);
            errMsg.setCorrelationId(msg.getCorrelationId());
        } else if (ex instanceof BucketAlreadyExistsException) {
            errMsg = new WalrusBucketErrorMessageType(((BucketAlreadyExistsException) ex).getBucketName(),
                    "BucketAlreadyExists",
                    "The requested bucket name is not available. The bucket namespace is shared by all users of the system. Please select a different name and try again.",
                    HttpStatus.SC_CONFLICT, msg.getCorrelationId(), ipAddr);
            errMsg.setCorrelationId(msg.getCorrelationId());
        } else if (ex instanceof BucketNotEmptyException) {
            errMsg = new WalrusBucketErrorMessageType(((BucketNotEmptyException) ex).getBucketName(),
                    "BucketNotEmpty", "The bucket you tried to delete is not empty.", HttpStatus.SC_CONFLICT,
                    msg.getCorrelationId(), ipAddr);
            errMsg.setCorrelationId(msg.getCorrelationId());
        } else if (ex instanceof PreconditionFailedException) {
            errMsg = new WalrusBucketErrorMessageType(((PreconditionFailedException) ex).getPrecondition(),
                    "PreconditionFailed", "At least one of the pre-conditions you specified did not hold.",
                    HttpStatus.SC_PRECONDITION_FAILED, msg.getCorrelationId(), ipAddr);
            errMsg.setCorrelationId(msg.getCorrelationId());
        } else if (ex instanceof NotModifiedException) {
            errMsg = new WalrusBucketErrorMessageType(((NotModifiedException) ex).getPrecondition(),
                    "NotModified", "Object Not Modified", HttpStatus.SC_NOT_MODIFIED, msg.getCorrelationId(),
                    ipAddr);
            errMsg.setCorrelationId(msg.getCorrelationId());
        } else if (ex instanceof TooManyBucketsException) {
            errMsg = new WalrusBucketErrorMessageType(((TooManyBucketsException) ex).getBucketName(),
                    "TooManyBuckets", "You have attempted to create more buckets than allowed.",
                    HttpStatus.SC_BAD_REQUEST, msg.getCorrelationId(), ipAddr);
            errMsg.setCorrelationId(msg.getCorrelationId());
        } else if (ex instanceof EntityTooLargeException) {
            errMsg = new WalrusBucketErrorMessageType(((EntityTooLargeException) ex).getEntityName(),
                    "EntityTooLarge", "Your proposed upload exceeds the maximum allowed object size.",
                    HttpStatus.SC_BAD_REQUEST, msg.getCorrelationId(), ipAddr);
            errMsg.setCorrelationId(msg.getCorrelationId());
        } else if (ex instanceof NoSuchEntityException) {
            errMsg = new WalrusBucketErrorMessageType(((NoSuchEntityException) ex).getBucketName(),
                    "NoSuchEntity", "The specified entity was not found", HttpStatus.SC_NOT_FOUND,
                    msg.getCorrelationId(), ipAddr);
            errMsg.setCorrelationId(msg.getCorrelationId());
        } else if (ex instanceof DecryptionFailedException) {
            errMsg = new WalrusBucketErrorMessageType(((DecryptionFailedException) ex).getValue(),
                    "Decryption Failed", "Fail", SC_DECRYPTION_FAILED, msg.getCorrelationId(), ipAddr);
            errMsg.setCorrelationId(msg.getCorrelationId());
        } else if (ex instanceof ImageAlreadyExistsException) {
            errMsg = new WalrusBucketErrorMessageType(((ImageAlreadyExistsException) ex).getValue(),
                    "Image Already Exists", "Fail", HttpStatus.SC_CONFLICT, msg.getCorrelationId(), ipAddr);
            errMsg.setCorrelationId(msg.getCorrelationId());
        } else if (ex instanceof NotImplementedException) {
            errMsg = new WalrusBucketErrorMessageType(((NotImplementedException) ex).getValue(),
                    "Not Implemented", "NA", HttpStatus.SC_NOT_IMPLEMENTED, msg.getCorrelationId(), ipAddr);
            errMsg.setCorrelationId(msg.getCorrelationId());
        } else {
            errMsg = new EucalyptusErrorMessageType(muleMsg.getComponentName(), msg, ex.getMessage());
        }
        replies.putMessage(errMsg);
    } catch (Exception e) {
        LOG.error(e, e);
    }
}

From source file:net.mm2d.dmsexplorer.ServerListActivity.java

private Collection<NetworkInterface> getWifiInterface() {
    final NetworkInfo ni = mConnectivityManager.getActiveNetworkInfo();
    if (ni == null || !ni.isConnected() || ni.getType() != ConnectivityManager.TYPE_WIFI) {
        return null;
    }/*from  w w w . j av a2 s . c o  m*/
    final InetAddress address = getWifiInetAddress();
    if (address == null) {
        return null;
    }
    final Enumeration<NetworkInterface> nis;
    try {
        nis = NetworkInterface.getNetworkInterfaces();
    } catch (final SocketException e) {
        return null;
    }
    while (nis.hasMoreElements()) {
        final NetworkInterface nif = nis.nextElement();
        try {
            if (nif.isLoopback() || nif.isPointToPoint() || nif.isVirtual() || !nif.isUp()) {
                continue;
            }
            final List<InterfaceAddress> ifas = nif.getInterfaceAddresses();
            for (final InterfaceAddress a : ifas) {
                if (a.getAddress().equals(address)) {
                    final Collection<NetworkInterface> c = new ArrayList<>();
                    c.add(nif);
                    return c;
                }
            }
        } catch (final SocketException ignored) {
        }
    }
    return null;
}

From source file:org.sakuli.actions.environment.CipherUtil.java

/**
 * fetch the local network interfaceLog and reads out the MAC of the chosen encryption interface.
 * Must be called before the methods {@link #encrypt(String)} or {@link #decrypt(String)}.
 *
 * @throws SakuliCipherException for wrong interface names and MACs.
 *//*  www .  ja  va 2s  . com*/
@PostConstruct
public void scanNetworkInterfaces() throws SakuliCipherException {
    Enumeration<NetworkInterface> networkInterfaces;
    try {
        interfaceName = checkEthInterfaceName();
        networkInterfaces = getNetworkInterfaces();
        while (networkInterfaces.hasMoreElements()) {
            NetworkInterface anInterface = networkInterfaces.nextElement();
            if (anInterface.getHardwareAddress() != null) {
                interfaceLog = interfaceLog + "\nNET-Interface " + anInterface.getIndex() + " - Name: "
                        + anInterface.getName() + "\t MAC: " + formatMAC(anInterface.getHardwareAddress())
                        + "\t VirtualAdapter: " + anInterface.isVirtual() + "\t Loopback: "
                        + anInterface.isLoopback() + "\t Desc.: " + anInterface.getDisplayName();
            }
            if (anInterface.getName().equals(interfaceName)) {
                macOfEncryptionInterface = anInterface.getHardwareAddress();
            }

        }
        if (macOfEncryptionInterface == null) {
            throw new SakuliCipherException(
                    "Cannot resolve MAC address ... please check your config of the property: "
                            + ActionProperties.ENCRYPTION_INTERFACE + "=" + interfaceName,
                    interfaceLog);
        }
    } catch (Exception e) {
        throw new SakuliCipherException(e, interfaceLog);
    }
}