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:org.kchine.rpf.PoolUtils.java

public static String getIPAddressFromNetworkInterfaces() {
    Vector<String> IPs = new Vector<String>();
    try {//from   w w  w  .jav a  2  s. c  o m
        NetworkInterface iface = null;
        for (Enumeration<?> ifaces = NetworkInterface.getNetworkInterfaces(); ifaces.hasMoreElements();) {
            iface = (NetworkInterface) ifaces.nextElement();
            InetAddress ia = null;
            for (Enumeration<?> ips = iface.getInetAddresses(); ips.hasMoreElements();) {
                ia = (InetAddress) ips.nextElement();
                boolean matches = isValidIPAddress(ia.getHostAddress()) && !isLoopBackIP(ia.getHostAddress());
                if (matches) {
                    IPs.add(ia.getHostAddress());
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    if (IPs.size() == 1)
        return IPs.elementAt(0);
    return null;
}

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

/**
 * @return the host address to bind this service to
 *//*from   w w  w .  j  a  v  a 2s  .  c o m*/
protected InetAddress determineHostAddress() {
    NetworkInterface iface = determineNetworkInterface();
    InetAddress raw = null;
    for (Enumeration<InetAddress> interfaceAddresses = iface.getInetAddresses(); interfaceAddresses
            .hasMoreElements();) {
        if (!interfaceAddresses.hasMoreElements()) {
            String msg = String.format("Unable to find any network address for interface[%s] {%s}",
                    iface.getName(), iface.getDisplayName());
            logger.error(msg);
            throw new IllegalStateException(msg);
        }
        raw = interfaceAddresses.nextElement();
        if (config.ipV6) {
            if (raw.getAddress().length == 6) {
                break;
            }
        } else if (raw.getAddress().length == 4) {
            break;
        }
    }
    if (raw == null) {
        String msg = String.format("Unable to find any network address for interface[%s] {%s}", iface.getName(),
                iface.getDisplayName());
        logger.error(msg);
        throw new IllegalStateException(msg);
    }
    InetAddress address;
    try {
        address = InetAddress.getByName(raw.getCanonicalHostName());
    } catch (UnknownHostException e) {
        String msg = String.format("Unable to resolve network address [%s] for interface[%s] {%s}", raw,
                iface.getName(), iface.getDisplayName());
        logger.error(msg, e);
        throw new IllegalStateException(msg, e);
    }
    return address;
}

From source file:org.archive.modules.fetcher.FetchHTTPTests.java

public void testHttpBindAddress() throws Exception {
    List<InetAddress> addrList = new ArrayList<InetAddress>();
    for (NetworkInterface ifc : Collections.list(NetworkInterface.getNetworkInterfaces())) {
        if (ifc.isUp()) {
            for (InetAddress addr : Collections.list(ifc.getInetAddresses())) {
                if (addr instanceof Inet4Address) {
                    addrList.add(addr);//from   w  ww.  ja  v  a 2 s  .  c  om
                }
            }
        }
    }
    if (addrList.size() < 2) {
        fail("unable to test binding to different local addresses: only " + addrList.size()
                + " addresses available");
    }
    for (InetAddress addr : addrList) {
        tryHttpBindAddress(addr.getHostAddress());
    }
}

From source file:com.aimluck.eip.mail.util.ALMailUtils.java

public static String getLocalurl() {
    EipMCompany record = ALEipUtils.getEipMCompany("1");
    String localurl = "";

    try {/*from ww w.  j a  va 2  s  .  com*/
        String ipaddress = record.getIpaddressInternal();
        if (null == ipaddress || "".equals(ipaddress)) {
            Enumeration<NetworkInterface> enuIfs = NetworkInterface.getNetworkInterfaces();
            if (null != enuIfs) {
                while (enuIfs.hasMoreElements()) {
                    NetworkInterface ni = enuIfs.nextElement();
                    Enumeration<InetAddress> enuAddrs = ni.getInetAddresses();
                    while (enuAddrs.hasMoreElements()) {
                        InetAddress in4 = enuAddrs.nextElement();
                        if (!in4.isLoopbackAddress()) {
                            ipaddress = in4.getHostAddress();
                        }
                    }
                }
            }
        }
        Integer port_internal = record.getPortInternal();
        if (null == port_internal) {
            port_internal = 80;
        }
        localurl = ALServletUtils.getAccessUrl(ipaddress, port_internal, false);
    } catch (SocketException e) {
        logger.error("ALMailUtils.getLocalurl", e);
    }
    return localurl;
}

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

private void onBoundHttpRequest() {
    NetworkInterface networkInterface = null;
    try {/*from  w  ww.j av a  2 s .c  om*/
        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:org.rifidi.utilities.device.DeviceAddressManager.java

/**
 * This method enumerates all existing devices in the system.
 *//*from w  w w  .  j  a v  a2  s.  c  o m*/
@SuppressWarnings("unchecked")
private void enumerateSystemDevices() {
    /* This is the set which will eventually become the new device set */
    Set<SystemDevice> enumeratedDevices = new TreeSet<SystemDevice>();

    /* Grab the previous devices and put them in an easy to use list form */
    List<SystemDevice> previouslyEnumeratedDevices = new ArrayList<SystemDevice>(this.systemDevices);

    /* Enumerate serial devices */
    if (this.serialEnabled) {
        Enumeration commPorts = CommPortIdentifier.getPortIdentifiers();
        while (commPorts.hasMoreElements()) {
            CommPortIdentifier curCommPort = (CommPortIdentifier) commPorts.nextElement();
            if (curCommPort.getPortType() == CommPortIdentifier.PORT_SERIAL) {
                /* Make a serial port so that we can get baud settings, etc. */
                RXTXPort tempPort = null;

                try {
                    /*
                     * Grab the serial port and get all of its current
                     * settings
                     */
                    tempPort = new RXTXPort(curCommPort.getName());

                    SystemSerialPort portToAdd = new SystemSerialPort(tempPort.getName(), tempPort.getName(),
                            SystemDevice.DeviceExistenceType.PREVIOUSLY_EXISTING, tempPort.getBaudRate(),
                            tempPort.getDataBits(), tempPort.getParity(), tempPort.getStopBits());

                    /* Check and see if the device already exists */
                    int existingDeviceIndex = previouslyEnumeratedDevices.indexOf(portToAdd);
                    if (existingDeviceIndex != -1) {
                        /* Grab that already existing device */
                        SystemSerialPort existingSerialDevice = (SystemSerialPort) previouslyEnumeratedDevices
                                .get(existingDeviceIndex);

                        /* Copy the creation state over */
                        portToAdd = new SystemSerialPort(tempPort.getName(), tempPort.getName(),
                                existingSerialDevice.getDeviceExistenceType(), tempPort.getBaudRate(),
                                tempPort.getDataBits(), tempPort.getParity(), tempPort.getStopBits());

                    }

                    tempPort.close();

                    /* Add to enumerated devices */
                    enumeratedDevices.add(portToAdd);

                } catch (PortInUseException e) {
                    logger.info(e.getMessage() + " (" + curCommPort.getName() + ")");

                }

            }

        }

    }

    /* Enumerate IP devices and all addresses. */
    /* Get all of the interfaces in the system and print them. */
    Enumeration<NetworkInterface> netInterfaces = null;

    try {
        netInterfaces = NetworkInterface.getNetworkInterfaces();

    } catch (SocketException e) {
        logger.warn(e.getMessage());

    }

    /* Check to see if we have interfaces to add to the device list. */
    if (netInterfaces != null) {
        /* Grab all of the interfaces and their network addresses */
        while (netInterfaces.hasMoreElements()) {
            /* Grab the current interface */
            NetworkInterface curInterface = netInterfaces.nextElement();

            /* Use a tree map for sorted IPs */
            Map<String, SystemNetworkInterface.NetworkAddressType> curInterfaceAddressMap;
            curInterfaceAddressMap = new TreeMap<String, SystemNetworkInterface.NetworkAddressType>();

            /* Get all of the addresses which this interface has */
            Enumeration<InetAddress> curInterfaceAddresses = curInterface.getInetAddresses();

            while (curInterfaceAddresses.hasMoreElements()) {
                /* Append the current address to map */
                InetAddress curAddress = curInterfaceAddresses.nextElement();
                curInterfaceAddressMap.put(curAddress.getHostAddress(),
                        SystemNetworkInterface.NetworkAddressType.PREVIOUSLY_EXISTING);

            }

            /* Create the new device */
            SystemNetworkInterface interfaceToAdd = new SystemNetworkInterface(curInterface.getDisplayName(),
                    curInterface.getName(), SystemDevice.DeviceExistenceType.PREVIOUSLY_EXISTING,
                    curInterfaceAddressMap);

            /* Check and see if the device already exists */
            int existingDeviceIndex = previouslyEnumeratedDevices.indexOf(interfaceToAdd);
            if (existingDeviceIndex != -1) {
                /* Grab that already existing device */
                SystemNetworkInterface existingNetworkInterface = (SystemNetworkInterface) previouslyEnumeratedDevices
                        .get(existingDeviceIndex);

                /* Copy over the existing device existence type */
                interfaceToAdd = null;
                interfaceToAdd = new SystemNetworkInterface(curInterface.getDisplayName(),
                        curInterface.getName(), existingNetworkInterface.getDeviceExistenceType(),
                        curInterfaceAddressMap);

                /* Copy over the address info */
                Iterator<String> addressIter = interfaceToAdd.getNetworkAddresses().keySet().iterator();
                /* Check each IP and see if it is previously existing */
                while (addressIter.hasNext()) {
                    String curAddress = addressIter.next();
                    SystemNetworkInterface.NetworkAddressType existingType = existingNetworkInterface
                            .getNetworkAddresses().get(curAddress);
                    /* Preserve the existing type */
                    if (existingType != null) {
                        interfaceToAdd.getNetworkAddresses().put(curAddress, existingType);

                    }

                }

            }

            /* Add the new device to the existing devices list */
            enumeratedDevices.add(interfaceToAdd);

        }

    }

    /* Blow out the old system devices */
    this.systemDevices.clear();

    /* Assign the new system devices */
    this.systemDevices = enumeratedDevices;

}

From source file:com.jagornet.dhcp.server.JagornetDhcpServer.java

/**
 * Gets all IPv6 network interfaces on the local host.
 * //from  w ww .  j  a v  a2  s. c o  m
 * @return the list NetworkInterfaces
 */
private List<NetworkInterface> getAllIPv6NetIfs() throws SocketException {
    List<NetworkInterface> netIfs = new ArrayList<NetworkInterface>();
    Enumeration<NetworkInterface> localInterfaces = NetworkInterface.getNetworkInterfaces();
    if (localInterfaces != null) {
        while (localInterfaces.hasMoreElements()) {
            NetworkInterface netIf = localInterfaces.nextElement();
            // for multicast, the loopback interface is excluded
            if (netIf.supportsMulticast() && !netIf.isLoopback()) {
                Enumeration<InetAddress> ifAddrs = netIf.getInetAddresses();
                while (ifAddrs.hasMoreElements()) {
                    InetAddress ip = ifAddrs.nextElement();
                    if (ip instanceof Inet6Address) {
                        netIfs.add(netIf);
                        break; // out to next interface
                    }
                }
            }
        }
    } else {
        log.error("No network interfaces found!");
    }
    return netIfs;
}

From source file:org.apache.nifi.web.server.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 .  j a  v a 2 s . co  m*/
                    }
                }
            }

            // ensure some hosts were found
            if (!hosts.isEmpty()) {
                String scheme = "http";
                if (props.getSslPort() != null && serverConnector.getPort() == props.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 has started, but the UI is not available on any hosts. Please verify the host properties.");
    } else {
        // log the ui location
        logger.info("NiFi has started. The UI is available at the following URLs:");
        for (final String url : urls) {
            logger.info(String.format("%s/nifi", url));
        }
    }
}

From source file:org.mortbay.ijetty.IJetty.java

License:asdf

private void printNetworkInterfaces() {
    try {//  w w w  .jav a 2  s  .  co  m
        Enumeration<NetworkInterface> nis = NetworkInterface.getNetworkInterfaces();
        for (NetworkInterface ni : Collections.list(nis)) {
            Enumeration<InetAddress> iis = ni.getInetAddresses();
            for (InetAddress ia : Collections.list(iis)) {
                consoleBuffer.append(formatJettyInfoLine("Network interface: %s: %s", ni.getDisplayName(),
                        ia.getHostAddress()));
            }
        }
    } catch (SocketException e) {
        Log.w(TAG, e);
    }
}

From source file:org.apache.cassandra.config.DatabaseDescriptor.java

private static InetAddress getNetworkInterfaceAddress(String intf, String configName, boolean preferIPv6)
        throws ConfigurationException {
    try {/*  ww  w. jav  a2 s . c om*/
        NetworkInterface ni = NetworkInterface.getByName(intf);
        if (ni == null)
            throw new ConfigurationException(
                    "Configured " + configName + " \"" + intf + "\" could not be found", false);
        Enumeration<InetAddress> addrs = ni.getInetAddresses();
        if (!addrs.hasMoreElements())
            throw new ConfigurationException(
                    "Configured " + configName + " \"" + intf + "\" was found, but had no addresses", false);

        /*
         * Try to return the first address of the preferred type, otherwise return the first address
         */
        InetAddress retval = null;
        while (addrs.hasMoreElements()) {
            InetAddress temp = addrs.nextElement();
            if (preferIPv6 && temp instanceof Inet6Address)
                return temp;
            if (!preferIPv6 && temp instanceof Inet4Address)
                return temp;
            if (retval == null)
                retval = temp;
        }
        return retval;
    } catch (SocketException e) {
        throw new ConfigurationException("Configured " + configName + " \"" + intf + "\" caused an exception",
                e);
    }
}