Java获取Windows或Linux下的IP地址

  Java获取Linux或Windows下的IP地址,详情如下

import lombok.extern.slf4j.Slf4j;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;


@Slf4j
public class IPUtils {

    public static String localIp = "";

    static {
        try {
            localIp = getLocalIp();
        }catch (Exception ex) {
            log.error("获取IP异常", ex);
        }
    }

    /**
     * 获取本机IP
     * @return
     * @throws UnknownHostException
     */
    public static String getLocalIp() throws UnknownHostException {
        if (isWindowsOS()) {
            return InetAddress.getLocalHost().getHostAddress();
        }else {
            return getLinuxLocalIp();
        }
    }

    /**
     * 获取Linux下的IP
     * @return
     */
    private static String getLinuxLocalIp() {
        String ip = "";
        try {
            for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
                NetworkInterface intf = en.nextElement();
                String name = intf.getName();
                if (!name.contains("docker") && !name.contains("lo")) {
                    for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                        InetAddress inetAddress = enumIpAddr.nextElement();
                        if (!inetAddress.isLinkLocalAddress()) {
                            String ipAddress = inetAddress.getHostAddress();
                            if (!ipAddress.contains("::") && !ipAddress.contains("0:0:") && !ipAddress.contains("fe80")) {
                                ip = ipAddress;
                            }
                        }
                    }
                }
            }
        } catch (SocketException ex) {
            log.error("获取Linux下的IP异常", ex);
            ip = "127.0.0.1";
        }
        log.info("Linux IP = {}", ip);
        return ip;
    }

    /**
     * 是否为Windows操作系统
     * @return
     */
    private static boolean isWindowsOS() {
        boolean isWindowOS = false;
        String osName = System.getProperty("os.name");
        if (osName.toLowerCase().indexOf("windows") > -1) {
            isWindowOS = true;
        }
        return isWindowOS;
    }

    public static void main(String[] args) throws UnknownHostException {
        String localIp = getLocalIp();
        System.out.println(localIp);
    }

}

 

posted @ 2023-11-09 09:43  无虑的小猪  阅读(158)  评论(0编辑  收藏  举报