Example usage for java.net NetworkInterface getByName

List of usage examples for java.net NetworkInterface getByName

Introduction

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

Prototype

public static NetworkInterface getByName(String name) throws SocketException 

Source Link

Document

Searches for the network interface with the specified name.

Usage

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

public static String[] getNicParams(final String nicName) {
    try {/* w  w  w. j  a  v a 2s. c o m*/
        final NetworkInterface nic = NetworkInterface.getByName(nicName);
        return getNetworkParams(nic);
    } catch (final SocketException e) {
        return null;
    }
}

From source file:org.apache.nifi.processors.standard.ListenSyslog.java

@OnScheduled
public void onScheduled(final ProcessContext context) throws IOException {
    final int port = context.getProperty(PORT).asInteger();
    final int bufferSize = context.getProperty(RECV_BUFFER_SIZE).asDataSize(DataUnit.B).intValue();
    final int maxChannelBufferSize = context.getProperty(MAX_SOCKET_BUFFER_SIZE).asDataSize(DataUnit.B)
            .intValue();//from  w  ww .  j  a v a  2s. com
    final int maxMessageQueueSize = context.getProperty(MAX_MESSAGE_QUEUE_SIZE).asInteger();
    final String protocol = context.getProperty(PROTOCOL).getValue();
    final String nicIPAddressStr = context.getProperty(NETWORK_INTF_NAME).evaluateAttributeExpressions()
            .getValue();
    final String charSet = context.getProperty(CHARSET).getValue();
    final String msgDemarcator = context.getProperty(MESSAGE_DELIMITER).getValue().replace("\\n", "\n")
            .replace("\\r", "\r").replace("\\t", "\t");
    messageDemarcatorBytes = msgDemarcator.getBytes(Charset.forName(charSet));

    final int maxConnections;
    if (UDP_VALUE.getValue().equals(protocol)) {
        maxConnections = 1;
    } else {
        maxConnections = context.getProperty(MAX_CONNECTIONS).asLong().intValue();
    }

    bufferPool = new LinkedBlockingQueue<>(maxConnections);
    for (int i = 0; i < maxConnections; i++) {
        bufferPool.offer(ByteBuffer.allocate(bufferSize));
    }

    parser = new SyslogParser(Charset.forName(charSet));
    syslogEvents = new LinkedBlockingQueue<>(maxMessageQueueSize);

    InetAddress nicIPAddress = null;
    if (!StringUtils.isEmpty(nicIPAddressStr)) {
        NetworkInterface netIF = NetworkInterface.getByName(nicIPAddressStr);
        nicIPAddress = netIF.getInetAddresses().nextElement();
    }

    // create either a UDP or TCP reader and call open() to bind to the given port
    final SSLContextService sslContextService = context.getProperty(SSL_CONTEXT_SERVICE)
            .asControllerService(SSLContextService.class);
    channelDispatcher = createChannelReader(protocol, bufferPool, syslogEvents, maxConnections,
            sslContextService, Charset.forName(charSet));
    channelDispatcher.open(nicIPAddress, port, maxChannelBufferSize);

    final Thread readerThread = new Thread(channelDispatcher);
    readerThread.setName("ListenSyslog [" + getIdentifier() + "]");
    readerThread.setDaemon(true);
    readerThread.start();
}

From source file:org.wso2.carbon.device.mgt.iot.agent.firealarm.communication.http.FireAlarmHTTPCommincator.java

/**
 * This is an overloaded method that fetches the public IPv4 address of the given network
 * interface//  ww w.j a v a 2s  .  c  o m
 *
 * @param networkInterfaceName the network-interface of whose IPv4 address is to be retrieved
 * @return the IP Address iof the device
 * @throws AgentCoreOperationException if any errors occur whilst trying to get details of the
 *                                     given network interface
 */
private String getDeviceIP(String networkInterfaceName) throws AgentCoreOperationException {
    String ipAddress = null;
    try {
        Enumeration<InetAddress> interfaceIPAddresses = NetworkInterface.getByName(networkInterfaceName)
                .getInetAddresses();
        for (; interfaceIPAddresses.hasMoreElements();) {
            InetAddress ip = interfaceIPAddresses.nextElement();
            ipAddress = ip.getHostAddress();
            if (log.isDebugEnabled()) {
                log.debug(AgentConstants.LOG_APPENDER + "IP Address: " + ipAddress);
            }

            if (TransportUtils.validateIPv4(ipAddress)) {
                return ipAddress;
            }
        }
    } catch (SocketException | NullPointerException exception) {
        String errorMsg = "Error encountered whilst trying to get IP Addresses of the network interface: "
                + networkInterfaceName
                + ".\nPlease check whether the name of the network interface used is correct";
        log.error(AgentConstants.LOG_APPENDER + errorMsg);
        throw new AgentCoreOperationException(errorMsg, exception);
    }

    return ipAddress;
}

From source file:com.chiralBehaviors.autoconfigure.AutoConfigure.java

/**
 * @return the network interface to bind this interface to.
 *//*from   ww  w  .ja  v a 2  s. c om*/
protected NetworkInterface determineNetworkInterface() {
    NetworkInterface iface;
    if (config.networkInterface == null) {
        try {
            iface = NetworkInterface.getByIndex(1);
        } catch (SocketException e) {
            String msg = String.format("Unable to obtain default network interface");
            logger.error(msg, e);
            throw new IllegalStateException(msg, e);
        }
    } else {
        try {
            iface = NetworkInterface.getByName(config.networkInterface);
        } catch (SocketException e) {
            String msg = String.format("Unable to obtain network interface[%s]", config.networkInterface);
            logger.error(msg, e);
            throw new IllegalStateException(msg, e);
        }
        if (iface == null) {
            String msg = String.format("Unable to find network interface [%s]", config.networkInterface);
            logger.error(msg);
            throw new IllegalStateException(msg);
        }
    }
    try {
        if (!iface.isUp()) {
            String msg = String.format("Network interface [%s] is not up!", iface.getName());
            logger.error(msg);
            throw new IllegalStateException(msg);
        }
    } catch (SocketException e) {
        String msg = String.format("Unable to determine if network interface [%s] is up", iface.getName());
        logger.error(msg);
        throw new IllegalStateException(msg);
    }
    logger.info(String.format("Network interface [%s] is up", iface.getDisplayName()));
    return iface;
}

From source file:org.alfresco.filesys.AbstractServerConfigurationBean.java

/**
 * Parse an adapter name string and return the matching address
 * //ww w .  j  a v  a  2 s . c  o m
 * @param adapter String
 * @return InetAddress
 * @exception InvalidConfigurationException
 */
protected final InetAddress parseAdapterName(String adapter) throws InvalidConfigurationException {

    NetworkInterface ni = null;

    try {
        ni = NetworkInterface.getByName(adapter);
    } catch (SocketException ex) {
        throw new InvalidConfigurationException("Invalid adapter name, " + adapter);
    }

    if (ni == null)
        throw new InvalidConfigurationException("Invalid network adapter name, " + adapter);

    // Get the IP address for the adapter

    InetAddress adapAddr = null;
    Enumeration<InetAddress> addrEnum = ni.getInetAddresses();

    while (addrEnum.hasMoreElements() && adapAddr == null) {

        // Get the current address

        InetAddress addr = addrEnum.nextElement();
        if (IPAddress.isNumericAddress(addr.getHostAddress()))
            adapAddr = addr;
    }

    // Check if we found the IP address to bind to

    if (adapAddr == null)
        throw new InvalidConfigurationException("Adapter " + adapter + " does not have a valid IP address");

    // Return the adapter address

    return adapAddr;
}

From source file:io.smartspaces.system.bootstrap.osgi.GeneralSmartSpacesSupportActivator.java

/**
 * Get the IP address for the system./* w  w  w.jav a2  s .  c  o  m*/
 *
 * @param systemConfiguration
 *          The system configuration
 *
 * @return host IP address
 */
private String getHostAddress(Configuration systemConfiguration) {
    try {
        String hostname = systemConfiguration
                .getPropertyString(SmartSpacesEnvironment.CONFIGURATION_NAME_HOST_NAME);
        if (hostname != null) {
            InetAddress address = InetAddress.getByName(hostname);
            return address.getHostAddress();
        }

        String hostInterface = systemConfiguration
                .getPropertyString(SmartSpacesEnvironment.CONFIGURATION_NAME_HOST_INTERFACE);
        if (hostInterface != null) {
            spaceEnvironment.getLog().formatInfo("Using network interface with name %s", hostInterface);
            NetworkInterface networkInterface = NetworkInterface.getByName(hostInterface);
            if (networkInterface != null) {
                for (InetAddress inetAddress : Collections.list(networkInterface.getInetAddresses())) {
                    if (inetAddress instanceof Inet4Address) {
                        return inetAddress.getHostAddress();
                    }
                }
            } else {
                spaceEnvironment.getLog().formatWarn("No network interface with name %s from configuration %s",
                        hostInterface, SmartSpacesEnvironment.CONFIGURATION_NAME_HOST_INTERFACE);

            }
        }

        // See if a single network interface. If so, we will use it.
        List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
        if (interfaces.size() == 1) {
            for (InetAddress inetAddress : Collections.list(interfaces.get(0).getInetAddresses())) {
                if (inetAddress instanceof Inet4Address) {
                    return inetAddress.getHostAddress();
                }
            }
        }

        return null;
    } catch (Exception e) {
        spaceEnvironment.getLog().error("Could not obtain IP address", e);
        return UNKNOWN_HOST_ADDRESS;
    }
}

From source file:com.android.development.Connectivity.java

private void onBoundHttpRequest() {
    NetworkInterface networkInterface = null;
    try {/*from   w  ww . j  av  a 2 s  . co m*/
        networkInterface = NetworkInterface.getByName("rmnet0");
        Log.d(TAG, "networkInterface is " + networkInterface);
    } catch (Exception e) {
        Log.e(TAG, " exception getByName: " + e);
        return;
    }
    if (networkInterface != null) {
        Enumeration inetAddressess = networkInterface.getInetAddresses();
        while (inetAddressess.hasMoreElements()) {
            Log.d(TAG, " inetAddress:" + ((InetAddress) inetAddressess.nextElement()));
        }
    }

    HttpParams httpParams = new BasicHttpParams();
    if (networkInterface != null) {
        ConnRouteParams.setLocalAddress(httpParams, networkInterface.getInetAddresses().nextElement());
    }
    HttpGet get = new HttpGet("http://www.bbc.com");
    HttpClient client = new DefaultHttpClient(httpParams);
    try {
        HttpResponse response = client.execute(get);
        Log.d(TAG, "response code = " + response.getStatusLine());
    } catch (Exception e) {
        Log.e(TAG, "Exception = " + e);
    }
}

From source file:com.android.development.Connectivity.java

private void onBoundSocketRequest() {
    NetworkInterface networkInterface = null;
    try {//from   ww  w. j av  a2s  . c om
        networkInterface = NetworkInterface.getByName("rmnet0");
    } catch (Exception e) {
        Log.e(TAG, "exception getByName: " + e);
        return;
    }
    if (networkInterface == null) {
        try {
            Log.d(TAG, "getting any networkInterface");
            networkInterface = NetworkInterface.getNetworkInterfaces().nextElement();
        } catch (Exception e) {
            Log.e(TAG, "exception getting any networkInterface: " + e);
            return;
        }
    }
    if (networkInterface == null) {
        Log.e(TAG, "couldn't find a local interface");
        return;
    }
    Enumeration inetAddressess = networkInterface.getInetAddresses();
    while (inetAddressess.hasMoreElements()) {
        Log.d(TAG, " addr:" + ((InetAddress) inetAddressess.nextElement()));
    }
    InetAddress local = null;
    InetAddress remote = null;
    try {
        local = networkInterface.getInetAddresses().nextElement();
    } catch (Exception e) {
        Log.e(TAG, "exception getting local InetAddress: " + e);
        return;
    }
    try {
        remote = InetAddress.getByName("www.flickr.com");
    } catch (Exception e) {
        Log.e(TAG, "exception getting remote InetAddress: " + e);
        return;
    }
    Log.d(TAG, "remote addr =" + remote);
    Log.d(TAG, "local addr =" + local);
    Socket socket = null;
    try {
        socket = new Socket(remote, 80, local, 6000);
    } catch (Exception e) {
        Log.e(TAG, "Exception creating socket: " + e);
        return;
    }
    try {
        PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
        out.println("Hi flickr");
    } catch (Exception e) {
        Log.e(TAG, "Exception writing to socket: " + e);
        return;
    }
}

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

private int handleUnboundOrLoopback(InetAddress bindIP, StringBuilder sReply) {

    int newStatusID = STATUS_ID_OK;

    InetAddress newBindIP = null;
    NetworkInterface newBindNetworkInterface = null;

    String s;/* w w w.j av  a  2  s  .co m*/

    if (bindIP.isAnyLocalAddress()) {
        addReply(sReply, CHAR_WARN, "pia.vuze.unbound");
    } else {
        addReply(sReply, CHAR_BAD, "pia.vuze.loopback");
    }

    try {
        NetworkAdmin networkAdmin = NetworkAdmin.getSingleton();

        // Find a bindable address that starts with 10.
        InetAddress[] bindableAddresses = networkAdmin.getBindableAddresses();

        for (InetAddress bindableAddress : bindableAddresses) {
            if (matchesVPNIP(bindableAddress)) {
                newBindIP = bindableAddress;
                newBindNetworkInterface = NetworkInterface.getByInetAddress(newBindIP);

                addReply(sReply, CHAR_GOOD, "pia.found.bindable.vpn", new String[] { "" + newBindIP });

                break;
            }
        }

        // Find a Network Interface that has an address that starts with 10.
        NetworkAdminNetworkInterface[] interfaces = networkAdmin.getInterfaces();

        boolean foundNIF = false;
        for (NetworkAdminNetworkInterface networkAdminInterface : interfaces) {
            NetworkAdminNetworkInterfaceAddress[] addresses = networkAdminInterface.getAddresses();
            for (NetworkAdminNetworkInterfaceAddress a : addresses) {
                InetAddress address = a.getAddress();
                if (address instanceof Inet4Address) {
                    if (matchesVPNIP(address)) {
                        s = texts.getLocalisedMessageText("pia.possible.vpn",
                                new String[] { "" + address, networkAdminInterface.getName() + " ("
                                        + networkAdminInterface.getDisplayName() + ")" });

                        if (newBindIP == null) {
                            foundNIF = true;
                            newBindIP = address;

                            // Either one should work
                            //newBindNetworkInterface = NetworkInterface.getByInetAddress(newBindIP);
                            newBindNetworkInterface = NetworkInterface
                                    .getByName(networkAdminInterface.getName());

                            s = CHAR_GOOD + " " + s + ". " + texts.getLocalisedMessageText("pia.assuming.vpn");
                        } else if (address.equals(newBindIP)) {
                            s = CHAR_GOOD + " " + s + ". " + texts.getLocalisedMessageText("pia.same.address");
                            foundNIF = true;
                        } else {
                            if (newStatusID != STATUS_ID_BAD) {
                                newStatusID = STATUS_ID_WARN;
                            }
                            s = CHAR_WARN + " " + s + ". "
                                    + texts.getLocalisedMessageText("pia.not.same.address");
                        }

                        addLiteralReply(sReply, s);

                        if (rebindNetworkInterface) {
                            // stops message below from being added, we'll rebind later
                            foundNIF = true;
                        }

                    }
                }
            }
        }

        if (!foundNIF) {
            addReply(sReply, CHAR_BAD, "pia.interface.not.found");
        }

        // 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, 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 == null ? "null"
                            : networkInterface.getName() + " (" + networkInterface.getDisplayName() + ")" });

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

                if (newBindIP == null) {
                    newBindIP = localAddress;
                    newBindNetworkInterface = networkInterface;

                    s = CHAR_GOOD + " " + s + " " + texts.getLocalisedMessageText("pia.assuming.vpn");
                } else if (localAddress.equals(newBindIP)) {
                    s = CHAR_GOOD + " " + s + " " + texts.getLocalisedMessageText("pia.same.address");
                } else {
                    // Vuze not bound. We already found a boundable address, but it's not this one
                    /* Possibly good case:
                     * - Vuze: unbound
                     * - Found Bindable: 10.100.1.6
                     * - Default Routing: 10.255.1.1
                     * -> Split network
                     */
                    if (newStatusID != STATUS_ID_BAD) {
                        newStatusID = STATUS_ID_WARN;
                    }
                    s = CHAR_WARN + " " + s + " " + texts.getLocalisedMessageText("pia.not.same.future.address")
                            + " " + texts.getLocalisedMessageText("default.routing.not.vpn.network.splitting")
                            + " " + texts.getLocalisedMessageText(
                                    "default.routing.not.vpn.network.splitting.unbound");
                }

                addLiteralReply(sReply, s);

            } else {
                s = CHAR_WARN + " " + s;
                if (!bindIP.isLoopbackAddress()) {
                    s += " " + texts.getLocalisedMessageText("default.routing.not.vpn.network.splitting");
                }

                if (newBindIP == null && foundNIF) {
                    if (newStatusID != STATUS_ID_BAD) {
                        newStatusID = STATUS_ID_WARN;
                    }
                    s += " " + texts
                            .getLocalisedMessageText("default.routing.not.vpn.network.splitting.unbound");
                }

                addLiteralReply(sReply, s);
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
        addReply(sReply, CHAR_BAD, "pia.nat.error", new String[] { e.toString() });
    }

    if (newBindIP == null) {
        addReply(sReply, CHAR_BAD, "pia.vpn.ip.detect.fail");
        return STATUS_ID_BAD;
    }

    rebindNetworkInterface(newBindNetworkInterface, newBindIP, sReply);
    return newStatusID;
}