如果提议连接的设备被指定为群组所有者,我们如何知道另一台设备的 IP 地址?我们可以获取群主的IP,但我不知道如何获取非群主的IP。因为请求连接的不是设备,所以它没有 WifiP2pInfo 类。它甚至不知道群主的IP。如何从该设备向群组所有者发送数据?
提前致谢!
最佳答案
您可以获取两个对等方的本地 IP 地址,然后将它们与组所有者 IP 进行比较。您可能已经知道,您可以使用这行代码轻松获取群组所有者 IP:
WifiP2pInfo.info.groupOwnerAddress.getHostAddress();
对于本地 IP,您可以简单地使用:
localIp = getDottedDecimalIP(getLocalIPAddress());
使用以下相关方法:
private byte[] 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()) {
if (inetAddress instanceof Inet4Address) {
return inetAddress.getAddress();
}
}
}
}
} catch (SocketException ex) {
// Log.e("AndroidNetworkAddressFactory", "getLocalIPAddress()", ex);
} catch (NullPointerException ex) {
// Log.e("AndroidNetworkAddressFactory", "getLocalIPAddress()", ex);
}
return null;
}
private String getDottedDecimalIP(byte[] ipAddr) {
if (ipAddr != null) {
String ipAddrStr = "";
for (int i = 0; i < ipAddr.length; i++) {
if (i > 0) {
ipAddrStr += ".";
}
ipAddrStr += ipAddr[i] & 0xFF;
}
return ipAddrStr;
} else {
return "null";
}
}
关于ip - 如何在 WiFi Direct 中获取非群组所有者的 IP 地址?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12946463/