Java IP Address Get getIp()

Here you can find the source of getIp()

Description

get Ip

License

Apache License

Declaration

public static String getIp() 

Method Source Code

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

import java.net.InetAddress;
import java.net.NetworkInterface;

import java.net.SocketException;

import java.util.Enumeration;

public class Main {
    public static String getIp() {
        String localip = null;// ??IP,????????IP????
        String netip = null;// ??IP
        try {/*w w w .j  ava2 s . co m*/
            Enumeration<NetworkInterface> netInterfaces = NetworkInterface.getNetworkInterfaces();
            InetAddress ip = null;
            boolean finded = false;// ??????IP
            while (netInterfaces.hasMoreElements() && !finded) {
                NetworkInterface ni = netInterfaces.nextElement();
                Enumeration<InetAddress> addresses = ni.getInetAddresses();
                while (addresses.hasMoreElements()) {
                    ip = addresses.nextElement();
                    if (!ip.isSiteLocalAddress() && !ip.isLoopbackAddress()
                            && ip.getHostAddress().indexOf(":") == -1) {// ??IP
                        netip = ip.getHostAddress();
                        finded = true;
                        break;
                    } else if (ip.isSiteLocalAddress() && !ip.isLoopbackAddress()
                            && ip.getHostAddress().indexOf(":") == -1) {// ??IP
                        localip = ip.getHostAddress();
                    }
                }
            }
        } catch (SocketException e) {
            e.printStackTrace();
        }
        if (netip != null && !"".equals(netip)) {
            return netip;
        } else {
            return localip;
        }
    }
}

Related

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