至今为止Android没有官方IP获取AP模式下的IP的接口,而且由于Android的开放性,各个厂商都发挥自己的想象力修改framework。所以默认的IP并不一定就是AP模式下的IP,要获取真实的IP就要另外想办法了。
先检查Wifi是否处于AP模式,然后运行下述代码:
private String getIP() {
// default IP for most device's softAp
String hotspotIp = "192.168.43.1";
try {
Enumeration<NetworkInterface> faces = NetworkInterface.getNetworkInterfaces();
while (faces.hasMoreElements()) {
NetworkInterface iface = faces.nextElement();
if (iface.isUp() && !iface.isLoopback() && !iface.isPointToPoint()) {
List<InterfaceAddress> listAddress = iface.getInterfaceAddresses();
for (InterfaceAddress address: listAddress) {
String ip = address.getAddress().toString();
Log.d("Stone", iface.getName() + " ip : " + ip);
if (ip.startsWith("/192.168")) {
hotspotIp = ip;
}
}
}
}
} catch (SocketException e) {
e.printStackTrace();
}
return hotspotIp.replace("/", "");
}
查看Android framework的代码可发现,192.168.43.1是AP模式下的默认IP,但是也不有部分不合流的厂商会修改它。没问题,当AP模式开启之后我们枚举所有IP,并且匹配192.168开头的IP作为结果。如果有厂商丧心病狂到将IP改为非192.168段的,还有一个方法是读取系统property wifi.interface的值,假如是wlan0,那么wlan0的IP就是结果。
在Android系统中,官方并未提供直接获取AP模式下IP的接口,由于各厂商定制化,默认IP可能不准确。可通过检查Wifi是否为AP模式,枚举所有IP并筛选192.168开头的IP,或读取wifi.interface属性来确定AP模式的IP地址。
6136

被折叠的 条评论
为什么被折叠?



