gpt4 book ai didi

java - 如何在Android中获取wifi热点的IP?

转载 作者:太空狗 更新时间:2023-10-29 22:57:27 26 4
gpt4 key购买 nike

正如标题所说...我试图在配置为热点时获取 wifi iface 的 IP。理想情况下,我想找到适用于所有手机的东西。

当然,WifiManager在获取AP的信息时是没用的。

幸运的是,我已经能够通过这样做获得所有接口(interface)的 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;
}

这段代码将打印所有接口(interface)的所有 IP(包括 Wifi 热点)。主要问题是我找不到识别 WiFi 接口(interface)的方法。这是一个问题,因为有些电话有多个接口(interface)(WiMax 等)。到目前为止,这是我尝试过的:

  • 按 wifi iface 显示名称过滤:这不是一个好的方法,因为显示名称会从一个设备更改为另一个设备(wlan0、eth0、wl0.1 等)。
  • 按其 MAC 地址过滤:几乎可以工作,但在某些设备上,热点 iface 没有 MAC 地址( iface.getHardwareAddress() 返回 null)...因此不是有效的解决方案。

有什么建议吗?

最佳答案

这是我获取 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;
}

这将为您提供任何 wifi 设备的IP 地址,这意味着它不仅仅用于热点。如果您连接到另一个 wifi 网络(意味着您未处于热点模式),它将返回一个 IP。

您应该先检查您是否处于 AP 模式。您可以为此使用此类:http://www.whitebyte.info/android/android-wifi-hotspot-manager-class

关于java - 如何在Android中获取wifi热点的IP?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9573196/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com