Java IP Address Get getIpAddress()

Here you can find the source of getIpAddress()

Description

get Ip Address

License

Apache License

Declaration

public static String getIpAddress() throws SocketException 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Collections;
import java.util.List;
import java.util.Optional;

public class Main {
    public static String getIpAddress() throws SocketException {
        List<NetworkInterface> networkInterfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
        return networkInterfaces.stream().filter(n -> n.getName().startsWith("en") || n.getName().startsWith("eth")
                || n.getName().startsWith("wlan")).filter(n -> {
                    try {
                        return !n.isLoopback() && n.isUp();
                    } catch (SocketException e1) {
                        return false;
                    }/*from   w ww. jav  a 2  s  .c o m*/
                }).map(n -> {
                    // Try to get the first IPv4 address
                    Optional<InetAddress> inetAddress = Collections.list(n.getInetAddresses()).stream()
                            .filter(a -> a instanceof Inet4Address).findFirst();

                    // Otherwise take the first IPv6 address
                    if (!inetAddress.isPresent()) {
                        inetAddress = Collections.list(n.getInetAddresses()).stream().findFirst();
                    }

                    return inetAddress.get().getHostAddress();
                }).filter(a -> a != null).findFirst().orElse("127.0.0.1");
    }
}

Related

  1. getIpAddress()
  2. getIpAddress()
  3. getIPAddress()
  4. getIpAddress()
  5. getIpAddress()
  6. getIpAddress()
  7. getIpAddress()
  8. getIpAddress()
  9. getIPAddress()