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();
    }

 

posted @ 2017-09-16 14:31  yshy  阅读(322)  评论(0编辑  收藏  举报