Example usage for java.net NetworkInterface getNetworkInterfaces

List of usage examples for java.net NetworkInterface getNetworkInterfaces

Introduction

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

Prototype

public static Enumeration<NetworkInterface> getNetworkInterfaces() throws SocketException 

Source Link

Document

Returns an Enumeration of all the interfaces on this machine.

Usage

From source file:Comman.Tool.java

public InetAddress getCurrentIp() {
    try {/*from   w w  w  .  ja  v  a 2 s. c  om*/
        Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
        while (networkInterfaces.hasMoreElements()) {
            NetworkInterface ni = (NetworkInterface) networkInterfaces.nextElement();
            Enumeration<InetAddress> nias = ni.getInetAddresses();
            while (nias.hasMoreElements()) {
                InetAddress ia = (InetAddress) nias.nextElement();
                if (!ia.isLinkLocalAddress() && !ia.isLoopbackAddress() && ia instanceof Inet4Address) {
                    return ia;
                }
            }
        }
    } catch (SocketException e) {
    }
    return null;
}

From source file:org.apache.smscserver.test.TestUtil.java

public static InetAddress findNonLocalhostIp() throws Exception {
    Enumeration<NetworkInterface> nifs = NetworkInterface.getNetworkInterfaces();

    while (nifs.hasMoreElements()) {
        NetworkInterface nif = nifs.nextElement();
        Enumeration<InetAddress> ips = nif.getInetAddresses();

        while (ips.hasMoreElements()) {
            InetAddress ip = ips.nextElement();
            if ((ip instanceof java.net.Inet4Address) && !ip.isLoopbackAddress()) {
                return ip;
            } else {
                // IPv6 not tested
            }/*from   w  w  w .  ja  v  a 2s.c o m*/
        }
    }

    return null;
}

From source file:com.offbynull.portmapper.natpmp.NatPmpReceiver.java

/**
 * Start listening for NAT-PMP events. This method blocks until {@link #stop() } is called.
 * @param listener listener to notify of events
 * @throws IOException if socket error occurs
 * @throws NullPointerException if any argument is {@code null}
 *///from w  w  w. j  a v a  2  s.c o  m
public void start(NatPmpEventListener listener) throws IOException {
    Validate.notNull(listener);

    MulticastSocket socket = null;
    try {
        final InetAddress group = InetAddress.getByName("224.0.0.1"); // NOPMD
        final int port = 5350;
        final InetSocketAddress groupAddress = new InetSocketAddress(group, port);

        socket = new MulticastSocket(port);

        if (!currentSocket.compareAndSet(null, socket)) {
            IOUtils.closeQuietly(socket);
            return;
        }

        socket.setReuseAddress(true);

        Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
        while (interfaces.hasMoreElements()) {
            NetworkInterface networkInterface = interfaces.nextElement();
            Enumeration<InetAddress> addrs = networkInterface.getInetAddresses();
            while (addrs.hasMoreElements()) { // make sure atleast 1 ipv4 addr bound to interface
                InetAddress addr = addrs.nextElement();

                try {
                    if (addr instanceof Inet4Address) {
                        socket.joinGroup(groupAddress, networkInterface);
                    }
                } catch (IOException ioe) { // NOPMD
                    // occurs with certain interfaces
                    // do nothing
                }
            }
        }

        ByteBuffer buffer = ByteBuffer.allocate(12);
        DatagramPacket data = new DatagramPacket(buffer.array(), buffer.capacity());

        while (true) {
            buffer.clear();
            socket.receive(data);
            buffer.position(data.getLength());
            buffer.flip();

            if (!data.getAddress().equals(gatewayAddress)) { // data isn't from our gateway, ignore
                continue;
            }

            if (buffer.remaining() != 12) { // data isn't the expected size, ignore
                continue;
            }

            int version = buffer.get(0);
            if (version != 0) { // data doesn't have the correct version, ignore
                continue;
            }

            int opcode = buffer.get(1) & 0xFF;
            if (opcode != 128) { // data doesn't have the correct op, ignore
                continue;
            }

            int resultCode = buffer.getShort(2) & 0xFFFF;
            switch (resultCode) {
            case 0:
                break;
            default:
                continue; // data doesn't have a successful result, ignore
            }

            listener.publicAddressUpdated(new ExternalAddressNatPmpResponse(buffer));
        }

    } catch (IOException ioe) {
        if (currentSocket.get() == null) {
            return; // ioexception caused by interruption/stop, so just return without propogating error up
        }

        throw ioe;
    } finally {
        IOUtils.closeQuietly(socket);
        currentSocket.set(null);
    }
}

From source file:copter.ServerConnection.java

private String getIpAddress() {
    String hostAddress = null;/*from   w ww .  j a v  a  2  s  . c om*/
    try {
        Enumeration<NetworkInterface> n = NetworkInterface.getNetworkInterfaces();
        for (; n.hasMoreElements();) {
            NetworkInterface e = n.nextElement();

            Enumeration<InetAddress> a = e.getInetAddresses();
            for (; a.hasMoreElements();) {
                InetAddress addr = a.nextElement();
                hostAddress = addr.getHostAddress();
                break;
            }
            break;
        }
    } catch (Exception ex) {
        logger.log(ex.getMessage());
    }
    return hostAddress;
}

From source file:io.github.gsteckman.rpi_rest.SsdpHandler.java

/**
 * Constructs a new instance of this class.
 *///from   w w  w. j a  va 2  s. co  m
private SsdpHandler() {
    LOG.info("Instantiating SsdpHandler");

    try {
        // Use first IPv4 address that isn't loopback, any, or link local as the server address
        Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
        while (interfaces.hasMoreElements() && serverAddress == null) {
            NetworkInterface i = interfaces.nextElement();
            Enumeration<InetAddress> addresses = i.getInetAddresses();
            while (addresses.hasMoreElements() && serverAddress == null) {
                InetAddress address = addresses.nextElement();
                if (address instanceof Inet4Address) {
                    if (!address.isAnyLocalAddress() && !address.isLinkLocalAddress()
                            && !address.isLoopbackAddress() && !address.isMulticastAddress()) {
                        serverAddress = address;
                    }
                }
            }
        }

        if (serverAddress == null) {
            LOG.warn("Server address unknown");
        }

        svc = SsdpService.forAllMulticastAvailableNetworkInterfaces(this);
        svc.listen();

        // setup Multicast for Notify messages
        notifySocket = new MulticastSocket();
        notifySocket.setTimeToLive(TTL);
        notifyTimer = new Timer("UPnP Notify Timer", true);
        notifyTimer.scheduleAtFixedRate(new NotifySender(), 5000, MAX_AGE * 1000 / 2);
    } catch (Exception e) {
        LOG.error("SsdpHandler in unknown state due to exception in constructor.", 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  va2 s. c  o m
            }
        }
    }
    return null;
}

From source file:org.wso2.carbon.device.mgt.iot.agent.firealarm.transport.TransportUtils.java

public static Map<String, String> getInterfaceIPMap() throws TransportHandlerException {

    Map<String, String> interfaceToIPMap = new HashMap<String, String>();
    Enumeration<NetworkInterface> networkInterfaces;
    String networkInterfaceName = "";
    String ipAddress;//w  w  w . ja va  2  s. c  o m

    try {
        networkInterfaces = NetworkInterface.getNetworkInterfaces();
    } catch (SocketException exception) {
        String errorMsg = "Error encountered whilst trying to get the list of network-interfaces";
        log.error(errorMsg);
        throw new TransportHandlerException(errorMsg, exception);
    }

    try {
        for (; networkInterfaces.hasMoreElements();) {
            networkInterfaceName = networkInterfaces.nextElement().getName();

            if (log.isDebugEnabled()) {
                log.debug("Network Interface: " + networkInterfaceName);
                log.debug("------------------------------------------");
            }

            Enumeration<InetAddress> interfaceIPAddresses = NetworkInterface.getByName(networkInterfaceName)
                    .getInetAddresses();

            for (; interfaceIPAddresses.hasMoreElements();) {
                ipAddress = interfaceIPAddresses.nextElement().getHostAddress();

                if (log.isDebugEnabled()) {
                    log.debug("IP Address: " + ipAddress);
                }

                if (TransportUtils.validateIPv4(ipAddress)) {
                    interfaceToIPMap.put(networkInterfaceName, ipAddress);
                }
            }

            if (log.isDebugEnabled()) {
                log.debug("------------------------------------------");
            }
        }
    } catch (SocketException exception) {
        String errorMsg = "Error encountered whilst trying to get the IP Addresses of the network "
                + "interface: " + networkInterfaceName;
        log.error(errorMsg);
        throw new TransportHandlerException(errorMsg, exception);
    }

    return interfaceToIPMap;
}

From source file:org.sonar.application.cluster.ClusterProperties.java

private static List<String> findAllLocalIPs() throws SocketException {
    Enumeration<NetworkInterface> netInterfaces = NetworkInterface.getNetworkInterfaces();
    List<String> localInterfaces = new ArrayList<>();

    while (netInterfaces.hasMoreElements()) {
        NetworkInterface networkInterface = netInterfaces.nextElement();
        Enumeration<InetAddress> ips = networkInterface.getInetAddresses();
        while (ips.hasMoreElements()) {
            InetAddress ip = ips.nextElement();
            localInterfaces.add(ip.getHostAddress());
        }//from w ww  .j a  va  2  s.  c om
    }
    return localInterfaces;
}

From source file:adams.core.net.InternetHelper.java

/**
 * Returns the host name determined from the network interfaces.
 *
 * @return       the host name, null if none found
 *///from   w w w  . j  a v a  2  s.c om
public static synchronized String getHostnameFromNetworkInterface() {
    String result;
    List<String> list;
    Enumeration<NetworkInterface> enmI;
    NetworkInterface intf;
    Enumeration<InetAddress> enmA;
    InetAddress addr;
    boolean found;

    result = null;

    if (m_HostnameNetworkInterface == null) {
        list = new ArrayList<>();
        found = false;
        try {
            enmI = NetworkInterface.getNetworkInterfaces();
            while (enmI.hasMoreElements()) {
                intf = enmI.nextElement();
                // skip non-active ones
                if (!intf.isUp())
                    continue;
                enmA = intf.getInetAddresses();
                while (enmA.hasMoreElements()) {
                    addr = enmA.nextElement();
                    list.add(addr.getHostName());
                    if (addr.getHostName().indexOf(':') == -1) {
                        result = addr.getHostName();
                        found = true;
                        break;
                    }
                }
                if (found)
                    break;
            }
        } catch (Exception e) {
            // ignored
        }

        if (result == null) {
            if (list.size() > 0)
                result = list.get(0);
            else
                result = "<unknown>";
        }

        m_HostnameNetworkInterface = result;
    } else {
        result = m_HostnameNetworkInterface;
    }

    return result;
}

From source file:org.springframework.cloud.dataflow.yarn.streamappmaster.EmbeddedAppmasterTrackService.java

private static String getDefaultAddress() {
    Enumeration<NetworkInterface> nets;
    try {/*from   ww  w  .  j  a  va2  s  . c  o m*/
        nets = NetworkInterface.getNetworkInterfaces();
    } catch (SocketException e) {
        return null;
    }
    NetworkInterface netinf;
    while (nets.hasMoreElements()) {
        netinf = nets.nextElement();
        boolean skip = false;
        try {
            skip = netinf.isPointToPoint();
        } catch (SocketException e) {
            skip = true;
        }
        if (skip) {
            continue;
        }
        Enumeration<InetAddress> addresses = netinf.getInetAddresses();
        while (addresses.hasMoreElements()) {
            InetAddress address = addresses.nextElement();
            if (!address.isAnyLocalAddress() && !address.isMulticastAddress()
                    && !(address instanceof Inet6Address)) {
                return address.getHostAddress();
            }
        }
    }
    return null;
}