获取android设备的IP


public class IPAddressUtils {
    public static String getLocalIpAddress() {
        try {
            String allIP = "";
            for (Enumeration<NetworkInterface> en = NetworkInterface
                    .getNetworkInterfaces(); en.hasMoreElements();) {
                NetworkInterface intf = en.nextElement();
                for (Enumeration<InetAddress> enumIpAddr = intf
                        .getInetAddresses(); enumIpAddr.hasMoreElements();) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    allIP += inetAddress.getHostAddress()+"\n";
                    if (!inetAddress.isLoopbackAddress()&&inetAddress instanceof Inet4Address) {
//                        return inetAddress.getHostAddress();
                    }
                }
            }
            return allIP;
        } catch (SocketException ex) {
            ex.printStackTrace();
        }
        return "获取失败";
    }
    
    public static String getIp(){  
        WifiManager wm=(WifiManager)MyApplication.getInstance().getApplicationContext()
                .getSystemService(Context.WIFI_SERVICE);  
        //检查Wifi状态    
        if(!wm.isWifiEnabled())  
            return "wifi未开启";  
        WifiInfo wi=wm.getConnectionInfo();  
        //获取32位整型IP地址    
        int ipAdd=wi.getIpAddress();  
        //把整型地址转换成“*.*.*.*”地址    
        String ip=intToIp(ipAdd);  
        return ip;  
    }  
    private static String intToIp(int i) {  
        return (i & 0xFF ) + "." +  
        ((i >> 8 ) & 0xFF) + "." +  
        ((i >> 16 ) & 0xFF) + "." +  
        ( i >> 24 & 0xFF) ;  
    }   
}  

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM