Java IP Address Get getLocalNetWorkIp()

Here you can find the source of getLocalNetWorkIp()

Description

get Local Net Work Ip

License

Apache License

Declaration

public static String getLocalNetWorkIp() 

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.util.Enumeration;

public class Main {
    private static String localIp;

    public static String getLocalNetWorkIp() {
        if (localIp != null) {
            return localIp;
        }/*  ww w  . j  a v a2  s .  c  om*/
        try {
            Enumeration<NetworkInterface> netInterfaces = NetworkInterface.getNetworkInterfaces();
            InetAddress ip = null;
            while (netInterfaces.hasMoreElements()) {
                NetworkInterface ni = (NetworkInterface) netInterfaces.nextElement();
                if ((!ni.isLoopback()) && (!ni.isVirtual())) {
                    Enumeration<InetAddress> addresss = ni.getInetAddresses();
                    while (addresss.hasMoreElements()) {
                        InetAddress address = (InetAddress) addresss.nextElement();
                        if ((address instanceof Inet4Address)) {
                            ip = address;
                            break;
                        }
                    }
                    if (ip != null) {
                        break;
                    }
                }
            }
            if (ip != null) {
                localIp = ip.getHostAddress();
            } else {
                localIp = "127.0.0.1";
            }
        } catch (Exception e) {
            localIp = "127.0.0.1";
        }
        return localIp;
    }
}

Related

  1. getLocalIPs()
  2. getLocalIps()
  3. getLocalIPs(boolean refresh)
  4. getLocalIpv4()
  5. getLocalIPv6Address()
  6. getLocalV4Ip()
  7. getLocalV4IpList()
  8. getLongIp(byte[] buff)
  9. getLongIp(String ipString)