Java IP Address Get getIPv4Address()

Here you can find the source of getIPv4Address()

Description

get I Pv Address

License

Open Source License

Declaration

public static String getIPv4Address() 

Method Source Code


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

public class Main {
    public static String getIPv4Address() {
        try {//from ww w.j  a  v  a2 s .  c  o m
            Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();

            NetworkInterface itf = null;
            while (en.hasMoreElements()) {
                itf = en.nextElement();
                if (!itf.isLoopback()) {
                    Enumeration<InetAddress> addresses = itf.getInetAddresses();
                    InetAddress addr = null;
                    while (addresses.hasMoreElements()) {
                        addr = addresses.nextElement();
                        if (!isIPv6Address(addr.getHostAddress())) {
                            return addr.getHostAddress();
                        }
                    }
                }
            }
        } catch (SocketException e) {
            e.printStackTrace();
            return null;
        }
        return null;
    }

    public static boolean isIPv6Address(String hostAddress) {
        return hostAddress.indexOf(":") != -1;
    }
}

Related

  1. getIpHostnameLocal()
  2. getIPList(String address)
  3. getIPList(String s, String s1)
  4. getIPs()
  5. getIPs()
  6. getIPV4Address(List addresses)
  7. getIPv4Address(NetworkInterface iface)
  8. getIPV4MainAddress(NetworkInterface ni)
  9. getIPv4MulticastGroup(int hash)