andriod中获取到ip地址、网关等信息的方法

来源:互联网 发布:淘宝春夏休闲运动鞋 编辑:程序博客网 时间:2024/05/21 21:43
<span style="font-size:14px;">获取到andriod中的ip,都要通过wifimanager来获取,通过getSystemService获得。</span>
<span style="font-size:14px;"></span>
<span style="font-size:14px;">得到wifimanager后可以直接获取到WifiInfo,这个时候就可以获取到android提供的wifi信息</span>
<span style="font-size:14px;"></span>
<span style="font-size:14px;">也可以获取DhcpInfo,是基于DHCP协议的信息对象,可以获取动态网络分配下的相关信息,如网关、ip等</span>
 <span style="font-size:12px;">//获取到wifimanager        WifiManager wifimanager = (WifiManager)getSystemService(WIFI_SERVICE);        //判断wifi是否开启        if(wifimanager.isWifiEnabled()){            //打开wifi            wifimanager.setWifiEnabled(true);        }        // WIFI_STATE_DISABLED,不可用        // WIFI_STATE_ENABLED可用,        // WIFI_STATE_UNKNOWN未知        int wifiState = wifimanager.getWifiState();                //获取到ip        WifiInfo wifiInfo = wifimanager.getConnectionInfo();        wifiInfo.getIpAddress();        int ipAddress = wifimanager.getDhcpInfo().ipAddress;        int gateway = wifimanager.getDhcpInfo().gateway;        //把ip转换成字符串形式,类似127.0.0.1        //android.text.format 包下的        String ipStr = Formatter.formatIpAddress(ipAddress);        String gateWay = Formatter.formatIpAddress(ipAddress);</span>
0 0
原创粉丝点击