sir*_*ion 15 java android wifi android-wifi
正如标题所说......我试图在配置为热点时能够获得wifi的IP.理想情况下,我想找到适合所有手机的东西.
当然,在从AP获取信息时,WifiManager是无用的.
幸运的是,通过这样做,我已经能够获得所有接口的IP:
public String getLocalIpAddress() {
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()) {
Log.d("IPs", inetAddress.getHostAddress() );
}
}
}
} catch (SocketException ex) {
Log.e(LOG_TAG, ex.toString());
}
return null;
}
Run Code Online (Sandbox Code Playgroud)
这段代码将打印所有接口的所有IP(包括Wifi热点).主要问题是我找不到识别WiFi接口的方法.这是一个问题,因为有些手机有多个接口(WiMax等).这是我到目前为止所尝试的:
有什么建议?
这是我为了获得wifi热点ip而做的事情:
public String getWifiApIpAddress() {
try {
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en
.hasMoreElements();) {
NetworkInterface intf = en.nextElement();
if (intf.getName().contains("wlan")) {
for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr
.hasMoreElements();) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress()
&& (inetAddress.getAddress().length == 4)) {
Log.d(TAG, inetAddress.getHostAddress());
return inetAddress.getHostAddress();
}
}
}
}
} catch (SocketException ex) {
Log.e(TAG, ex.toString());
}
return null;
}
Run Code Online (Sandbox Code Playgroud)
这将为您提供任何 wifi设备的IP地址,这意味着它不仅仅适用于热点.如果你连接到另一个wifi网络(意味着你不在热点模式),它将返回一个IP.
你应该先检查你是否处于AP模式.您可以使用此类:http://www.whitebyte.info/android/android-wifi-hotspot-manager-class
这是一个可能的解决方案,用于WiFiManager ConnectionInfo查找相应的NetworkInterface.
如果您只需要 IP,那么您可以使用:
WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
int ipAddress = wifiInfo.getIpAddress();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
18870 次 |
| 最近记录: |