Java 获取本机IP地址

public static String getIP() {
        StringBuilder sb = new StringBuilder("");
        
        try {
            Enumeration allNetInterfaces = NetworkInterface.getNetworkInterfaces();
            InetAddress ip = null;
            while (allNetInterfaces.hasMoreElements()) {
                NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();
                
                Enumeration addresses = netInterface.getInetAddresses();
                while (addresses.hasMoreElements()) {
                    ip = (InetAddress) addresses.nextElement();
                    if (ip != null && ip instanceof Inet4Address) {
                        sb.append(ip.getHostAddress()).append(",");
                    }
                }
            }
            
            if(sb.length()>0){
                sb.setLength(sb.length()-1);
            }
        } catch (SocketException ex) {
            Logger.getLogger(T02.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        return sb.toString();
    }
原文地址:https://www.cnblogs.com/yshyee/p/7531252.html