Example usage for java.net NetworkInterface getInetAddresses

List of usage examples for java.net NetworkInterface getInetAddresses

Introduction

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

Prototype

public Enumeration<InetAddress> getInetAddresses() 

Source Link

Document

Get an Enumeration with all or a subset of the InetAddresses bound to this network interface.

Usage

From source file:com.seleuco.mame4droid.NetPlay.java

public String getIPAddress() {
    try {//from w  w  w .ja  v  a2s .  com
        Enumeration<NetworkInterface> ifaceList;
        NetworkInterface selectedIface = null;

        // First look for a WLAN interface
        ifaceList = NetworkInterface.getNetworkInterfaces();
        while (selectedIface == null && ifaceList.hasMoreElements()) {
            NetworkInterface intf = ifaceList.nextElement();
            if (intf.getName().startsWith("wlan")) {
                List<InetAddress> addrs = Collections.list(intf.getInetAddresses());
                for (InetAddress addr : addrs) {
                    if (!addr.isLoopbackAddress()) {
                        String sAddr = addr.getHostAddress().toUpperCase();
                        boolean isIPv4 = InetAddressUtils.isIPv4Address(sAddr);
                        if (isIPv4)
                            return sAddr;
                    }
                }
            }
        }

        // If we didn't find that, look for an Ethernet interface
        ifaceList = NetworkInterface.getNetworkInterfaces();
        while (selectedIface == null && ifaceList.hasMoreElements()) {
            NetworkInterface intf = ifaceList.nextElement();
            if (intf.getName().startsWith("eth")) {
                List<InetAddress> addrs = Collections.list(intf.getInetAddresses());
                for (InetAddress addr : addrs) {
                    if (!addr.isLoopbackAddress()) {
                        String sAddr = addr.getHostAddress().toUpperCase();
                        boolean isIPv4 = InetAddressUtils.isIPv4Address(sAddr);
                        if (isIPv4)
                            return sAddr;
                    }
                }
            }
        }

        List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
        for (NetworkInterface intf : interfaces) {
            List<InetAddress> addrs = Collections.list(intf.getInetAddresses());
            for (InetAddress addr : addrs) {
                if (!addr.isLoopbackAddress()) {
                    String sAddr = addr.getHostAddress().toUpperCase();
                    boolean isIPv4 = InetAddressUtils.isIPv4Address(sAddr);
                    if (isIPv4)
                        return sAddr;
                }
            }
        }
    } catch (Exception ex) {
    }
    return null;
}

From source file:org.apache.nifi.registry.jetty.JettyServer.java

private void dumpUrls() throws SocketException {
    final List<String> urls = new ArrayList<>();

    for (Connector connector : server.getConnectors()) {
        if (connector instanceof ServerConnector) {
            final ServerConnector serverConnector = (ServerConnector) connector;

            Set<String> hosts = new HashSet<>();

            // determine the hosts
            if (StringUtils.isNotBlank(serverConnector.getHost())) {
                hosts.add(serverConnector.getHost());
            } else {
                Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
                if (networkInterfaces != null) {
                    for (NetworkInterface networkInterface : Collections.list(networkInterfaces)) {
                        for (InetAddress inetAddress : Collections.list(networkInterface.getInetAddresses())) {
                            hosts.add(inetAddress.getHostAddress());
                        }//from  w w w.ja v  a  2  s. co m
                    }
                }
            }

            // ensure some hosts were found
            if (!hosts.isEmpty()) {
                String scheme = "http";
                if (properties.getSslPort() != null && serverConnector.getPort() == properties.getSslPort()) {
                    scheme = "https";
                }

                // dump each url
                for (String host : hosts) {
                    urls.add(String.format("%s://%s:%s", scheme, host, serverConnector.getPort()));
                }
            }
        }
    }

    if (urls.isEmpty()) {
        logger.warn(
                "NiFi Registry has started, but the UI is not available on any hosts. Please verify the host properties.");
    } else {
        // log the ui location
        logger.info("NiFi Registry has started. The UI is available at the following URLs:");
        for (final String url : urls) {
            logger.info(String.format("%s/nifi-registry", url));
        }
    }
}

From source file:com.poinsart.votar.VotarMain.java

public String getWifiIp() {
    Enumeration<NetworkInterface> en = null;
    try {//  w w w  .ja v  a2  s .  co m
        en = NetworkInterface.getNetworkInterfaces();
    } catch (SocketException e) {
        return null;
    }
    while (en.hasMoreElements()) {
        NetworkInterface intf = en.nextElement();
        if (intf.getName().contains("wlan")) {
            for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
                InetAddress inetAddress = enumIpAddr.nextElement();
                if (!inetAddress.isLoopbackAddress() && (inetAddress.getAddress().length == 4)) {
                    //Log.d("VotAR Main", inetAddress.getHostAddress());
                    return inetAddress.getHostAddress().toString();
                }
            }
        }
    }
    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();/*ww w .ja v  a 2  s.  c o  m*/
    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:com.elixsr.portforwarder.forwarding.ForwardingService.java

private InetSocketAddress generateFromIpUsingInterface(String interfaceName, int port)
        throws SocketException, ObjectNotFoundException {

    String address = null;/*from   w w  w  .  j  av  a  2 s .  co m*/
    InetSocketAddress inetSocketAddress;

    for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
        NetworkInterface intf = en.nextElement();

        Log.d(TAG, intf.getDisplayName() + " vs " + interfaceName);
        if (intf.getDisplayName().equals(interfaceName)) {

            Log.i(TAG, "Found the relevant Interface. Will attempt to fetch IP Address");

            for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {

                InetAddress inetAddress = enumIpAddr.nextElement();

                address = new String(inetAddress.getHostAddress().toString());

                if (address != null & address.length() > 0 && inetAddress instanceof Inet4Address) {

                    inetSocketAddress = new InetSocketAddress(address, port);
                    return inetSocketAddress;
                }
            }
        }
    }

    //Failed to find the relevant interface
    //TODO: complete
    //        Toast.makeText(this, "Could not find relevant network interface.",
    //                Toast.LENGTH_LONG).show();
    throw new ObjectNotFoundException("Could not find IP Address for Interface " + interfaceName);
}

From source file:org.ohthehumanity.carrie.CarrieActivity.java

public String getLocalIpAddress() {
    try {/*w  w w.j a  v  a2s.  co m*/
        for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en
                .hasMoreElements();) {

            NetworkInterface intf = en.nextElement();
            for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {

                InetAddress inetAddress = enumIpAddr.nextElement();
                if (!inetAddress.isLoopbackAddress()) {
                    return inetAddress.getHostAddress();
                }
            }
        }
    } catch (SocketException ex) {
        //Log.e(TAG, ex.toString());
    }
    return "";
}

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

/**
 * Get the IP address for the system./*from   ww  w.  j  a  va  2s.co  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:org.psit.transwatcher.TransWatcher.java

private String getBroadcastIP() {
    String myIP = null;/*from   w w  w.  j a  v  a  2  s  . c  o  m*/

    try {
        Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
        while (interfaces.hasMoreElements() && myIP == null) {
            NetworkInterface current = interfaces.nextElement();
            notifyMessage(current.toString());
            notifyMessage("Name: " + current.getName());
            if (!current.isUp() || current.isLoopback() || current.isVirtual()
                    || !current.getName().startsWith("wl"))
                continue;
            Enumeration<InetAddress> addresses = current.getInetAddresses();
            while (addresses.hasMoreElements()) {
                InetAddress current_addr = addresses.nextElement();
                if (current_addr.isLoopbackAddress())
                    continue;
                if (current_addr instanceof Inet4Address) {
                    myIP = current_addr.getHostAddress();
                    break;
                }
            }
        }
    } catch (Exception exc) {
        notifyMessage("Error determining network interfaces:\n");
    }

    if (myIP != null) {
        // broadcast for IPv4
        StringTokenizer st = new StringTokenizer(myIP, ".");
        StringBuffer broadcastIP = new StringBuffer();
        // hate that archaic string puzzle
        broadcastIP.append(st.nextElement());
        broadcastIP.append(".");
        broadcastIP.append(st.nextElement());
        broadcastIP.append(".");
        broadcastIP.append(st.nextElement());
        broadcastIP.append(".");
        broadcastIP.append("255");
        return broadcastIP.toString();
    }

    return null;
}