从 ICS 开始,引入了 Wi-Fi Direct。正常情况下,我们使用WifiP2pManager
类对Wi-Fi Direct进行操作,但连接后似乎只能获取GroupOwner IP地址。但是,实际上,任何设备都来协商成为GroupOwner。在上层应用中,我们需要获取peer的IP地址,或者组中每个peer的IP地址,这样我们就可以和他们发送/通信了。
如何在 Wi-Fi Direct 中获取每个 IP 地址?包括自己的 IP 地址和组中的每个对等方?
最佳答案
我遇到了同样的问题。由于两个设备都知道组所有者的 ip,因此已经可以向组所有者发送消息。您发送的第一条消息可以包含其他设备的 IP 地址;从此,双向通信成为可能。
这是在 java 中检索您的 ip 的一种可能性:
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) { // fix for Galaxy Nexus. IPv4 is easy to use :-)
return inetAddress.getAddress();
}
//return inetAddress.getHostAddress().toString(); // Galaxy Nexus returns IPv6
}
}
}
} catch (SocketException ex) {
//Log.e("AndroidNetworkAddressFactory", "getLocalIPAddress()", ex);
} catch (NullPointerException ex) {
//Log.e("AndroidNetworkAddressFactory", "getLocalIPAddress()", ex);
}
return null;
}
private String getDottedDecimalIP(byte[] ipAddr) {
//convert to dotted decimal notation:
String ipAddrStr = "";
for (int i=0; i<ipAddr.length; i++) {
if (i > 0) {
ipAddrStr += ".";
}
ipAddrStr += ipAddr[i]&0xFF;
}
return ipAddrStr;
}
ip = getDottedDecimalIP(getLocalIPAddress());
将此 ip 包装在一个 Serializable 对象中并将其发送给组所有者,就像发送任何其他对象一样。考虑这是您的 wifi-direct 协议(protocol)的第一步......现在,组所有者也有一个 IP 可以发送答案。
这对我有用,尽管我认为我必须自己实现这个很奇怪,而且我只能轻松找到组所有者 ip(info.groupOwnerAddress.getHostAddress();//带有 WifiP2pInfo 实例的信息)。也许有一种类似的方法可以检索其他同行的 ip,但我找不到。如果有请联系我。
祝你好运……
关于android - Wi-Fi Direct场景下如何获取每台设备的IP地址?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10053385/