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.castlemock.web.basis.web.mvc.controller.AbstractController.java

/**
 * The method returns the local address (Not link local address, not loopback address) which the server is deployed on.
 * If the method does not find any INet4Address that is neither link local address and loopback address, the method
 * will return the the address 127.0.0.1
 * @return Returns the local address or 127.0.0.1 if no address was found
 * @throws SocketException Upon failing to extract network interfaces
 *//*from   w  w w.j  a  v  a2s.c o m*/
public String getHostAddress() throws SocketException {
    if (endpointAddress != null && !endpointAddress.isEmpty()) {
        return endpointAddress;
    }

    final Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
    while (networkInterfaces.hasMoreElements()) {
        final NetworkInterface networkInterface = networkInterfaces.nextElement();
        final Enumeration<InetAddress> addresses = networkInterface.getInetAddresses();
        while (addresses.hasMoreElements()) {
            final InetAddress address = addresses.nextElement();
            if (!address.isLinkLocalAddress() && !address.isLoopbackAddress()
                    && address instanceof Inet4Address) {
                return address.getHostAddress();
            }
        }
    }

    return LOCAL_ADDRESS;
}

From source file:org.trafodion.rest.util.NetworkConfiguration.java

public InetAddress getInetAddress(NetworkInterface ni) throws Exception {
    InetAddress inet = null;//  w  ww  . j  ava  2  s  . c om
    Enumeration<InetAddress> rawAdrs = ni.getInetAddresses();
    while (rawAdrs.hasMoreElements()) {
        inet = rawAdrs.nextElement();
        LOG.info("Match Found interface [" + ni.toString() + "," + ni.getDisplayName() + ","
                + inet.getCanonicalHostName() + "," + inet.getHostAddress() + "]");
    }
    matchedInterface = true;
    return inet;
}

From source file:com.commonsware.android.webserver.simple.WebServerService.java

private void raiseStartedEvent() {
    ServerStartedEvent event = new ServerStartedEvent();

    try {//from  ww w  . j ava 2 s.  c om
        for (Enumeration<NetworkInterface> enInterfaces = NetworkInterface.getNetworkInterfaces(); enInterfaces
                .hasMoreElements();) {
            NetworkInterface ni = enInterfaces.nextElement();

            for (Enumeration<InetAddress> enAddresses = ni.getInetAddresses(); enAddresses.hasMoreElements();) {
                InetAddress addr = enAddresses.nextElement();

                if (addr instanceof Inet4Address) {
                    event.addUrl("http://" + addr.getHostAddress() + ":4999");
                }
            }
        }
    } catch (SocketException e) {
        Log.e(getClass().getSimpleName(), "Exception in IP addresses", e);
    }

    EventBus.getDefault().removeAllStickyEvents();
    EventBus.getDefault().postSticky(event);
}

From source file:org.nebula.framework.core.HeartbeatWorker.java

private void acquireIp() {
    Enumeration<NetworkInterface> net = null;
    try {/* w ww. j  a v  a  2  s. c  o  m*/
        net = NetworkInterface.getNetworkInterfaces();

        while (net.hasMoreElements()) {
            NetworkInterface element = net.nextElement();
            Enumeration<InetAddress> addresses = element.getInetAddresses();
            while (addresses.hasMoreElements()) {

                InetAddress ipAddress = addresses.nextElement();
                if (ipAddress instanceof Inet4Address) {

                    if (ipAddress.isSiteLocalAddress()) {
                        ip = ipAddress.getHostAddress();
                    }
                }
            }
        }
    } catch (Exception e) {
        // ignore
    }
}

From source file:org.mule.module.http.functional.listener.HttpListenerConfigFunctionalTestCase.java

private String getNonLocalhostIp() {
    try {// w w w  .j a v a  2s . c om
        Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces();
        for (NetworkInterface networkInterface : Collections.list(nets)) {
            final Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses();
            while (inetAddresses.hasMoreElements()) {
                InetAddress inetAddress = inetAddresses.nextElement();
                if (!inetAddress.isLoopbackAddress()
                        && IPADDRESS_PATTERN.matcher(inetAddress.getHostAddress()).find()) {
                    return inetAddress.getHostAddress();
                }
            }
        }
        throw new RuntimeException("Could not find network interface different from localhost");
    } catch (SocketException e) {
        throw new RuntimeException(e);
    }
}

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

/**
 * ?(eth0, eth1..)??//from   w  w w  .j a  v  a2  s  .  co 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:com.orangelabs.rcs.platform.network.AndroidNetworkFactory.java

/**
 * Returns the local IP address of a given network interface
 * /*from   w w w .j  av a  2s.c  o m*/
 * @param dnsEntry remote address to find an according local socket address
  * @param type the type of the network interface, should be either
  *        {@link android.net.ConnectivityManager#TYPE_WIFI} or {@link android.net.ConnectivityManager#TYPE_MOBILE}
 * @return Address
 */
// Changed by Deutsche Telekom
public String getLocalIpAddress(DnsResolvedFields dnsEntry, int type) {
    String ipAddress = null;
    try {
        // What kind of remote address (P-CSCF) are we trying to reach?
        boolean isIpv4 = InetAddressUtils.isIPv4Address(dnsEntry.ipAddress);

        // check all available interfaces
        for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); (en != null)
                && en.hasMoreElements();) {
            NetworkInterface netIntf = (NetworkInterface) en.nextElement();
            for (Enumeration<InetAddress> addr = netIntf.getInetAddresses(); addr.hasMoreElements();) {
                InetAddress inetAddress = addr.nextElement();
                ipAddress = IpAddressUtils.extractHostAddress(inetAddress.getHostAddress());
                // if IP address version doesn't match to remote address
                // version then skip
                if (!inetAddress.isLoopbackAddress() && !inetAddress.isLinkLocalAddress()
                        && (InetAddressUtils.isIPv4Address(ipAddress) == isIpv4)) {
                    String intfName = netIntf.getDisplayName().toLowerCase();
                    // some devices do list several interfaces though only
                    // one is active
                    if (((type == ConnectivityManager.TYPE_WIFI) && intfName.startsWith("wlan"))
                            || ((type == ConnectivityManager.TYPE_MOBILE) && !intfName.startsWith("wlan"))) {
                        return ipAddress;
                    }
                }
            }
        }
    } catch (Exception e) {
        if (logger.isActivated()) {
            logger.error("getLocalIpAddress failed with ", e);
        }
    }
    return ipAddress;
}

From source file:com.chicm.cmraft.core.ClusterMemberManager.java

private void initLocalAddresses() {
    try {/*from   w  w  w .  j a  v  a  2 s  . c  om*/
        Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
        while (interfaces.hasMoreElements()) {
            NetworkInterface inet = (NetworkInterface) interfaces.nextElement();
            Enumeration<InetAddress> addrs = inet.getInetAddresses();
            while (addrs.hasMoreElements()) {
                InetAddress addr = (InetAddress) addrs.nextElement();
                LOG.debug("local address:" + addr.getHostAddress());
                LOG.debug("local address:" + addr.getHostName());
                if (!addr.getHostAddress().isEmpty()) {
                    localAddresses.add(addr.getHostAddress());
                }
                if (!addr.getHostName().isEmpty()) {
                    localAddresses.add(addr.getHostName());
                }
            }
        }

        InetAddress inetAddress = InetAddress.getLocalHost();
        localAddresses.add(inetAddress.getHostAddress());
        localAddresses.add(inetAddress.getCanonicalHostName());
        localAddresses.add(inetAddress.getHostName());

        inetAddress = InetAddress.getLoopbackAddress();
        localAddresses.add(inetAddress.getHostAddress());
        localAddresses.add(inetAddress.getCanonicalHostName());
        localAddresses.add(inetAddress.getHostName());
    } catch (SocketException | UnknownHostException e) {
        LOG.error("", e);
    }
}

From source file:org.ebayopensource.scc.track.TrackerClient.java

private InetAddress getInetAddress() {
    Enumeration<NetworkInterface> eni = null;
    try {/*from   w ww . j  a  v  a2s  .c o m*/
        eni = NetworkInterface.getNetworkInterfaces();
        while (eni.hasMoreElements()) {
            NetworkInterface n = eni.nextElement();
            Enumeration<InetAddress> eia = n.getInetAddresses();
            while (eia.hasMoreElements()) {
                InetAddress current = eia.nextElement();
                if (current.isSiteLocalAddress()) {
                    return current;
                }
            }
        }
        return InetAddress.getLocalHost();
    } catch (SocketException | UnknownHostException ex) {
        LOGGER.warn("Failed to get IP address.", ex);
        return null;
    }
}

From source file:org.openhab.io.hueemulation.internal.HueEmulationUpnpServer.java

@Override
public void run() {
    MulticastSocket recvSocket = null;
    // since jupnp shares port 1900, lets use a different port to send UDP packets on just to be safe.
    DatagramSocket sendSocket = null;
    byte[] buf = new byte[1000];
    DatagramPacket recv = new DatagramPacket(buf, buf.length);
    while (running) {
        try {/*from w ww  .j  ava  2 s. c o  m*/
            if (discoveryIp != null && discoveryIp.trim().length() > 0) {
                address = InetAddress.getByName(discoveryIp);
            } else {
                Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
                while (interfaces.hasMoreElements()) {
                    NetworkInterface ni = interfaces.nextElement();
                    Enumeration<InetAddress> addresses = ni.getInetAddresses();
                    while (addresses.hasMoreElements()) {
                        InetAddress addr = addresses.nextElement();
                        if (addr instanceof Inet4Address && !addr.isLoopbackAddress()) {
                            address = addr;
                            break;
                        }
                    }
                }
            }
            InetSocketAddress socketAddr = new InetSocketAddress(MULTI_ADDR, UPNP_PORT_RECV);
            recvSocket = new MulticastSocket(UPNP_PORT_RECV);
            recvSocket.joinGroup(socketAddr, NetworkInterface.getByInetAddress(address));
            sendSocket = new DatagramSocket();
            while (running) {
                recvSocket.receive(recv);
                if (recv.getLength() > 0) {
                    String data = new String(recv.getData());
                    logger.trace("Got SSDP Discovery packet from {}:{}", recv.getAddress().getHostAddress(),
                            recv.getPort());
                    if (data.startsWith("M-SEARCH")) {
                        String msg = String.format(discoString, "http://" + address.getHostAddress().toString()
                                + ":" + System.getProperty("org.osgi.service.http.port") + discoPath, usn);
                        DatagramPacket response = new DatagramPacket(msg.getBytes(), msg.length(),
                                recv.getAddress(), recv.getPort());
                        try {
                            logger.trace("Sending to {} : {}", recv.getAddress().getHostAddress(), msg);
                            sendSocket.send(response);
                        } catch (IOException e) {
                            logger.error("Could not send UPNP response", e);
                        }
                    }
                }
            }
        } catch (SocketException e) {
            logger.error("Socket error with UPNP server", e);
        } catch (IOException e) {
            logger.error("IO Error with UPNP server", e);
        } finally {
            IOUtils.closeQuietly(recvSocket);
            IOUtils.closeQuietly(sendSocket);
            if (running) {
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                }
            }
        }
    }
}