通过WifiManager,可以获取DhcpInfo参数,
从而获取android IP地址及网关等信息 。
DhcpInfo参数中,gateway,netmask,ipAddress都是int型。
因此需要进行类型转换,转换成诸如172.22.198.5的IP地址。
Android已经提供了类型转换方法,即:
android.text.format.Formatter.formatIpAddress(dhcpInfo.ipAddress)等;
public String getIPAddressInfo() {
WifiManager wifi_service = (WifiManager) getApplicationContext()
.getSystemService(Context.WIFI_SERVICE);
DhcpInfo dhcpInfo = wifi_service.getDhcpInfo();
WifiInfo wifiinfo = wifi_service.getConnectionInfo();
Log.d(TAG, "Wifi info----->" + wifiinfo.getIpAddress());
Log.d(TAG,
"DHCP info gateway----->"
+ Formatter.formatIpAddress(dhcpInfo.gateway));
Log.d(TAG,
"DHCP info netmask----->"
+ Formatter.formatIpAddress(dhcpInfo.netmask));
Log.d(TAG,
"DHCP info ipAddress----->"
+ Formatter.formatIpAddress(dhcpInfo.ipAddress));
return Formatter.formatIpAddress(dhcpInfo.ipAddress);
}
但dhcpinfo参数值如何转换为相应的int型呢?
原理参见下图:
原文中没有涉及java转换方法,自己补充一个方法:
public static long FormatDHCPIp(int fir,int sec,int thd,int four){
BigInteger s = BigInteger.valueOf(fir);
s = s.add(BigInteger.valueOf(sec*256)).add(BigInteger.valueOf(thd*256*256)).
add(BigInteger.valueOf(four*256*256*256));
System.out.println("s.longValue():"+s.longValue());
return s.longValue();
}
制作成APK,网络参数和对应的int值一目了然:
对应的apk下载地址:http://download.csdn.net/detail/singleton1900/6924931