Kagami

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理
public String getLocalIpAddress() {  
        String ipaddress="";
       
        
    try {  
        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.getAddress().length==4) {  
                        ipaddress=inetAddress.getHostAddress().toString();  
                }  
            }  
        }  
    } catch (SocketException ex) {  
        Log.e("WifiPreference IpAddress", ex.toString());  
    }  
   
    return ipaddress; 
    }

判断条件inetAddress.getAddress().length==4是判断是否是IP4地址,因为4.0会有IP6地址

这方法总觉得太麻烦,不过我试过ConnectivityManager和其它的都没法获得,哪位有简单方法获得的话,可以在评论里写下

posted on 2013-04-24 15:40  Kagami  阅读(521)  评论(1编辑  收藏  举报