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:com.groupon.odo.proxylib.Utils.java

/**
 * This function returns the first external IP address encountered
 *
 * @return IP address or null/* w  w  w. j a  va  2 s  . com*/
 * @throws Exception
 */
public static String getPublicIPAddress() throws Exception {
    final String IPV4_REGEX = "\\A(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)(\\.(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)){3}\\z";

    String ipAddr = null;
    Enumeration e = NetworkInterface.getNetworkInterfaces();
    while (e.hasMoreElements()) {
        NetworkInterface n = (NetworkInterface) e.nextElement();
        Enumeration ee = n.getInetAddresses();
        while (ee.hasMoreElements()) {
            InetAddress i = (InetAddress) ee.nextElement();

            // Pick the first non loop back address
            if ((!i.isLoopbackAddress() && i.isSiteLocalAddress()) || i.getHostAddress().matches(IPV4_REGEX)) {
                ipAddr = i.getHostAddress();
                break;
            }
        }
        if (ipAddr != null) {
            break;
        }
    }

    return ipAddr;
}

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

public static InetAddress[] getAllLocalInetAddresses() {
    final List<InetAddress> addrList = new ArrayList<InetAddress>();
    try {/*from w w  w.jav a  2s .c  om*/
        for (final NetworkInterface ifc : IteratorUtil
                .enumerationAsIterable(NetworkInterface.getNetworkInterfaces())) {
            if (ifc.isUp() && !ifc.isVirtual()) {
                for (final InetAddress addr : IteratorUtil.enumerationAsIterable(ifc.getInetAddresses())) {
                    addrList.add(addr);
                }
            }
        }
    } catch (final SocketException e) {
        s_logger.warn("SocketException in getAllLocalInetAddresses().", e);
    }

    final InetAddress[] addrs = new InetAddress[addrList.size()];
    if (addrList.size() > 0) {
        System.arraycopy(addrList.toArray(), 0, addrs, 0, addrList.size());
    }
    return addrs;
}

From source file:NotificationMessage.java

public static InetAddress getIPAddress() throws SocketException {
    InetAddress ip = null;//from w w  w.  j ava2s  . c  o  m
    Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces();
    for (NetworkInterface netint : Collections.list(nets)) {
        if (netint.getName().equals("wlan0")) {
            Enumeration<InetAddress> inetAddresses = netint.getInetAddresses();

            for (InetAddress inetAddress : Collections.list(inetAddresses)) {
                return inetAddress;
            }
            //displayInterfaceInformation(netint);

        }
        continue;

    }
    return ip;
}

From source file:org.kei.android.phone.cellhistory.towers.MobileNetworkInfo.java

/** Get IP For mobile */
public static String getMobileIP(final boolean useIPv4) {
    try {/*  w ww .ja  va  2 s  .c o  m*/
        final List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
        for (final NetworkInterface intf : interfaces) {
            final List<InetAddress> addrs = Collections.list(intf.getInetAddresses());
            for (final InetAddress addr : addrs) {
                if (!addr.isLoopbackAddress()) {
                    final String sAddr = addr.getHostAddress().toUpperCase(Locale.US);
                    final boolean isIPv4 = InetAddressUtils.isIPv4Address(sAddr);
                    if (useIPv4) {
                        if (isIPv4)
                            return sAddr;
                    } else {
                        if (!isIPv4) {
                            final int delim = sAddr.indexOf('%'); // drop ip6 port suffix
                            return delim < 0 ? sAddr : sAddr.substring(0, delim);
                        }
                    }
                }
            }
        }
    } catch (final Exception ex) {
        Log.e(MobileNetworkInfo.class.getSimpleName(), "Exception in Get IP Address: " + ex.getMessage(), ex);
    }
    return TowerInfo.UNKNOWN;
}

From source file:org.eclipse.smarthome.binding.lifx.internal.LifxLightDiscovery.java

@Override
protected void activate(Map<String, Object> configProperties) {
    super.activate(configProperties);

    broadcastAddresses = new ArrayList<InetSocketAddress>();
    interfaceAddresses = new ArrayList<InetAddress>();

    Enumeration<NetworkInterface> networkInterfaces = null;
    try {// www  .ja va  2s.  c  o m
        networkInterfaces = NetworkInterface.getNetworkInterfaces();
    } catch (SocketException e) {
        logger.debug("An exception occurred while discovering LIFX lights : '{}'", e.getMessage());
    }
    if (networkInterfaces != null) {
        while (networkInterfaces.hasMoreElements()) {
            NetworkInterface iface = networkInterfaces.nextElement();
            try {
                if (iface.isUp() && !iface.isLoopback()) {
                    for (InterfaceAddress ifaceAddr : iface.getInterfaceAddresses()) {
                        if (ifaceAddr.getAddress() instanceof Inet4Address) {
                            logger.debug("Adding '{}' as interface address with MTU {}", ifaceAddr.getAddress(),
                                    iface.getMTU());
                            if (iface.getMTU() > bufferSize) {
                                bufferSize = iface.getMTU();
                            }
                            interfaceAddresses.add(ifaceAddr.getAddress());
                            if (ifaceAddr.getBroadcast() != null) {
                                logger.debug("Adding '{}' as broadcast address", ifaceAddr.getBroadcast());
                                broadcastAddresses
                                        .add(new InetSocketAddress(ifaceAddr.getBroadcast(), BROADCAST_PORT));
                            }
                        }
                    }
                }
            } catch (SocketException e) {
                logger.debug("An exception occurred while discovering LIFX lights : '{}'", e.getMessage());
            }
        }
    }
}

From source file:com.jagornet.dhcp.client.ClientSimulatorV6.java

/**
 * Instantiates a new test client./*from  ww w . ja v  a 2s.  com*/
 *
 * @param args the args
 * @throws Exception the exception
 */
public ClientSimulatorV6(String[] args) throws Exception {
    DEFAULT_NETIF = NetworkInterface.getNetworkInterfaces().nextElement();
    DEFAULT_ADDR = DhcpConstants.ALL_DHCP_RELAY_AGENTS_AND_SERVERS;

    setupOptions();

    if (!parseOptions(args)) {
        formatter = new HelpFormatter();
        String cliName = this.getClass().getName();
        formatter.printHelp(cliName, options);
        System.exit(0);
    }

    try {
        start();
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:org.powertac.tournament.services.TournamentProperties.java

private String getTourneyUrl() {
    if (!properties.getProperty("tourney.location", "").isEmpty()) {
        return properties.getProperty("tourney.location");
    }//from   w w w  .ja  v  a 2s.co  m

    String tourneyUrl = "http://%s:8080/TournamentScheduler/";
    String address = "127.0.0.1";
    try {
        Enumeration<NetworkInterface> n = NetworkInterface.getNetworkInterfaces();
        while (n.hasMoreElements()) {
            NetworkInterface e = n.nextElement();
            if (e.getName().startsWith("lo")) {
                continue;
            }

            Enumeration<InetAddress> a = e.getInetAddresses();
            while (a.hasMoreElements()) {
                InetAddress addr = a.nextElement();
                if (addr.getClass().getName().equals("java.net.Inet4Address")) {
                    address = addr.getHostAddress();
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        messages.add("Error getting Tournament Location!");
    }

    return String.format(tourneyUrl, address);
}

From source file:org.wso2.carbon.analytics.dataservice.indexing.AnalyticsDataIndexer.java

private String getLocalUniqueId() {
    String id = null;//from w w w .j a va 2  s.  c  o  m
    Enumeration<NetworkInterface> interfaces;
    NetworkInterface nif;
    try {
        interfaces = NetworkInterface.getNetworkInterfaces();
        while (interfaces.hasMoreElements()) {
            nif = interfaces.nextElement();
            if (!nif.isLoopback()) {
                byte[] addr = nif.getHardwareAddress();
                if (addr != null) {
                    id = this.byteArrayToHexString(addr);
                }
                /* only try first valid one, if we can't get it from here, 
                 * we wont be able to get it */
                break;
            }
        }
    } catch (SocketException ignore) {
        /* ignore */
    }
    if (id == null) {
        log.warn("CANNOT LOOK UP UNIQUE LOCAL ID USING A VALID NETWORK INTERFACE HARDWARE ADDRESS, "
                + "REVERTING TO LOCAL SINGLE NODE MODE, THIS WILL NOT WORK PROPERLY IN A CLUSTER, "
                + "AND MAY CAUSE INDEX CORRUPTION");
        /* a last effort to get a unique number, Java system properties should also take in account of the 
         * server's port offset */
        id = LOCAL_NODE_ID + ":" + (System.getenv().hashCode() + System.getProperties().hashCode());
    }
    return id;
}

From source file:com.amazonaws.services.kinesis.aggregators.consumer.AggregatorConsumer.java

public void configure() throws Exception {
    if (!isConfigured) {
        validateConfig();/*from  w  w w . j  av  a 2s. c om*/

        if (this.positionInStream != null) {
            streamPosition = InitialPositionInStream.valueOf(this.positionInStream);
        } else {
            streamPosition = InitialPositionInStream.LATEST;
        }

        // append the environment name to the application name
        if (environmentName != null) {
            appName = String.format("%s-%s", appName, environmentName);
        }

        // ensure the JVM will refresh the cached IP values of AWS resources
        // (e.g. service endpoints).
        java.security.Security.setProperty("networkaddress.cache.ttl", "60");

        String workerId = NetworkInterface.getNetworkInterfaces() + ":" + UUID.randomUUID();
        LOG.info("Using Worker ID: " + workerId);

        // obtain credentials using the default provider chain or the
        // credentials provider supplied
        AWSCredentialsProvider credentialsProvider = this.credentialsProvider == null
                ? new DefaultAWSCredentialsProviderChain()
                : this.credentialsProvider;

        LOG.info("Using credentials with Access Key ID: "
                + credentialsProvider.getCredentials().getAWSAccessKeyId());

        config = new KinesisClientLibConfiguration(appName, streamName, credentialsProvider, workerId)
                .withInitialPositionInStream(streamPosition).withKinesisEndpoint(kinesisEndpoint);

        config.getKinesisClientConfiguration().setUserAgent(StreamAggregator.AWSApplication);

        if (regionName != null) {
            Region region = Region.getRegion(Regions.fromName(regionName));
            config.withRegionName(region.getName());
        }

        if (maxRecords != -1)
            config.withMaxRecords(maxRecords);

        // initialise the Aggregators
        aggGroup = buildAggregatorsFromConfig();

        LOG.info(String.format(
                "Amazon Kinesis Aggregators Managed Client prepared for %s on %s in %s (%s) using %s Max Records",
                config.getApplicationName(), config.getStreamName(), config.getRegionName(),
                config.getWorkerIdentifier(), config.getMaxRecords()));

        isConfigured = true;
    }
}

From source file:com.git.original.common.utils.IPUtils.java

/**
 * ?IP?/*from w w  w .j  a va  2  s .  c om*/
 * <p>
 * :<br/>
 * 1. 192.xxx.xxx.xxx<br>
 * 2. 172.xxx.xxx.xxx<br>
 * 3. 10.xxx.xxx.xxx<br>
 * other<br>
 * 
 * @return ipv4?
 * @throws SocketException
 */
private static synchronized int doGetLocalIp() throws SocketException {
    if (localIp != 0) {
        return localIp;
    }

    Integer ipStartWith10 = null;
    Integer ipStartWith172 = null;
    Integer other = null;

    /*
     * ?IP?
     */
    Enumeration<NetworkInterface> interfaceEnum = NetworkInterface.getNetworkInterfaces();
    while (interfaceEnum.hasMoreElements()) {
        NetworkInterface netInterface = interfaceEnum.nextElement();
        if (!netInterface.isUp()) {
            continue;
        }

        Enumeration<InetAddress> addrEnum = netInterface.getInetAddresses();
        while (addrEnum.hasMoreElements()) {
            InetAddress addr = addrEnum.nextElement();
            String hostAddr = addr.getHostAddress();

            if (hostAddr.startsWith("192.")) {
                localIp = ByteUtils.toInt(addr.getAddress());
                return localIp;
            } else if (ipStartWith172 == null && hostAddr.startsWith("172.")) {
                ipStartWith172 = ByteUtils.toInt(addr.getAddress());
            } else if (ipStartWith10 == null && hostAddr.startsWith("10.")) {
                ipStartWith10 = ByteUtils.toInt(addr.getAddress());
            } else if (other == null && (addr instanceof Inet4Address)) {
                other = ByteUtils.toInt(addr.getAddress());
            }
        }
    }

    if (ipStartWith172 != null) {
        localIp = ipStartWith172;
        return localIp;
    } else if (ipStartWith10 != null) {
        localIp = ipStartWith10;
        return localIp;
    } else if (other != null) {
        localIp = other;
        return localIp;
    }

    throw new RuntimeException("can not get Local Server IPv4 Address");
}