Java IP Address Get getLocalIp()

Here you can find the source of getLocalIp()

Description

get Local Ip

License

Open Source License

Declaration

public static String getLocalIp() 

Method Source Code


//package com.java2s;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;

public class Main {
    public static String getLocalIp() {
        String ret = null;/*from   w w w.j a v  a  2  s  .co m*/
        try {
            Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces();
            while (nets.hasMoreElements()) {
                NetworkInterface net = nets.nextElement();
                if (net.isLoopback() || net.isVirtual() || net.getName().startsWith("vmnet")
                        || net.getName().startsWith("docker")) {
                    continue;
                }
                Enumeration<InetAddress> nis = net.getInetAddresses();
                while (nis.hasMoreElements()) {
                    InetAddress ip = nis.nextElement();
                    if (ip.isSiteLocalAddress()) {
                        ret = ip.getHostAddress();
                    }
                }
            }
        } catch (SocketException e) {
            ret = getLocalIpSimple();
        }
        return ret;
    }

    /**
     * @return
     */
    public static String getLocalIpSimple() {
        try {
            return InetAddress.getLocalHost().getHostAddress();
        } catch (UnknownHostException e) {
            throw new RuntimeException("Get ip failed!", e);
        }
    }
}

Related

  1. getLocalhostIp()
  2. getLocalHostIp()
  3. getLocalHostIPAdress()
  4. getLocalHostIps()
  5. getLocalHostIps()
  6. getLocalIp()
  7. getLocalIP()
  8. getLocalIP()
  9. getLocalIP()