獲取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