wifi下获取IP地址

原创
2017/01/18 16:42
阅读数 8

还是直接上代码

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 "";
    }

然后添加权限

<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"/>  
展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部