Java IP Address Get getStrLocalIP()

Here you can find the source of getStrLocalIP()

Description

get Str Local IP

License

Apache License

Declaration

public static String getStrLocalIP() throws SocketException, UnknownHostException 

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.net.UnknownHostException;
import java.util.Enumeration;

public class Main {

    public static String getStrLocalIP() throws SocketException, UnknownHostException {
        String ip = null;/*  w  ww.java 2s .  c  o m*/
        Enumeration<NetworkInterface> enuNI = NetworkInterface.getNetworkInterfaces();
        begin: while (enuNI.hasMoreElements()) {
            NetworkInterface ni = (NetworkInterface) enuNI.nextElement();
            Enumeration<InetAddress> enuAddress = ni.getInetAddresses();
            while (enuAddress.hasMoreElements()) {
                InetAddress address = enuAddress.nextElement();
                if (!address.isSiteLocalAddress() && !address.isLoopbackAddress()
                        && address.getHostAddress().indexOf(":") == -1) {
                    ip = address.getHostAddress();
                    break begin;
                }
            }
        }

        if (ip == null) {
            InetAddress addr = InetAddress.getLocalHost();
            ip = addr.getHostAddress();
        }
        return ip;
    }
}

Related

  1. getPublicIP()
  2. getPublicIP2()
  3. getPublicIPAddress()
  4. getPublicIps()
  5. getPublicIpViaHttp()
  6. getVisibleIp()
  7. getWinLocalIP()
  8. getWinLocalIp()