Java IP Address Get getHostIP()

Here you can find the source of getHostIP()

Description

get Host IP

License

Apache License

Declaration

public static HashSet<String> getHostIP() 

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;
import java.util.HashSet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {

    public static HashSet<String> getHostIP() {
        HashSet ipAdd = new HashSet();
        try {//  w  w  w  .ja v  a2s .c o  m
            for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en
                    .hasMoreElements();) {
                NetworkInterface intf = en.nextElement();
                for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress() && !inetAddress.isLinkLocalAddress()
                            && inetAddress.isSiteLocalAddress()) {
                        if (isIpv4(inetAddress.getHostAddress())) {
                            ipAdd.add(inetAddress.getHostAddress());
                        }
                    }
                }
            }
        } catch (SocketException ex) {
        }
        return ipAdd;
    }

    public static boolean isIpv4(String ipAddress) {

        String ip = "^(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|[1-9])\\."
                + "(00?\\d|1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\."
                + "(00?\\d|1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\."
                + "(00?\\d|1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)$";

        Pattern pattern = Pattern.compile(ip);
        Matcher matcher = pattern.matcher(ipAddress);
        return matcher.matches();

    }
}

Related

  1. getExternalIPAddress()
  2. getFirstLocalNonLoopbackIpAddress()
  3. getFirstNonLoopbackAddress(boolean preferIpv4, boolean preferIPv6)
  4. getFirstNonLoopBackAddress(boolean preferIpv4, boolean preferIPv6)
  5. getHostIp()
  6. getHostIp()
  7. getHostIP()
  8. getHostIP()
  9. getHostIpAddress()