wifi下獲取IP地址

仍是直接上代碼android

public String getIpAddress(){
        String ipAddress = "";
        try{
            ipAddress = wifiIpAddress();
            if(ipAddress!=null&&ipAddress.trim().length()>0){
            }else{
                ipAddress = this.GPRSIpAddress();
            }
        }catch(Exception ex){
             
        }
        return ipAddress;//有IP返回就聯網
    }
    private String wifiIpAddress(){
        String ip = "";
        //獲取wifi服務
        WifiManager wifiManager = (WifiManager)(context).getSystemService(Context.WIFI_SERVICE);
        //判斷wifi是否開啓
        if (wifiManager.isWifiEnabled()) {
            //wifiManager.setWifiEnabled(true);  
            WifiInfo wifiInfo = wifiManager.getConnectionInfo();     
            int ipAddress = wifiInfo.getIpAddress(); 
            ip = intToIp(ipAddress);
        }
        return ip;
    }
    private String intToIp(int i) {
        return (i & 0xFF ) + "." +     
      ((i >> 8 ) & 0xFF) + "." +     
      ((i >> 16 ) & 0xFF) + "." +     
      ( i >> 24 & 0xFF) ;
    }
     
    private String GPRSIpAddress(){
        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()){
                       return inetAddress.getHostAddress().toString();
                   }
               }
           }
        }catch (SocketException ex){
            Log.d("GPRSIpAddress IpAddress", ex.toString());
        }
        return "";
    }

而後添加權限oop

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />  
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
相關文章
相關標籤/搜索