Java IP Address Get getLocalIp()

Here you can find the source of getLocalIp()

Description

get Local Ip

License

Open Source License

Return

The non-loopback IP address of the local host or null if none is available.

Declaration

public static String getLocalIp() 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.net.*;
import java.util.Enumeration;

public class Main {
    /**/*www.j a va2s.  co m*/
     * @return The non-loopback IP address of the local host or {@code null}
     * if none is available.
     */
    public static String getLocalIp() {
        try {
            Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();

            while (interfaces.hasMoreElements()) {
                NetworkInterface current = interfaces.nextElement();

                if (!current.isUp() || current.isLoopback() || current.isVirtual()) {
                    continue;
                }

                Enumeration<InetAddress> addresses = current.getInetAddresses();
                while (addresses.hasMoreElements()) {
                    InetAddress address = addresses.nextElement();
                    if (address.isLoopbackAddress() || !(address instanceof Inet4Address)) {
                        continue;
                    }

                    return address.getHostAddress();
                }
            }
        } catch (SocketException ex) {
            ex.printStackTrace();
            throw new RuntimeException(ex);
        }

        return null;
    }
}

Related

  1. getLocalIP()
  2. getLocalIP()
  3. getLocalIP()
  4. getLocalIP()
  5. getLocalIP()
  6. getLocalIP()
  7. getLocalIp()
  8. getLocalIp()
  9. getLocalIp()