如何在WiFi Direct中获取非组所有者的IP地址?

5
如果设备被指定为组所有者并提出连接,我们该如何知道其他设备的IP地址?我们可以获取组所有者的IP,但我不知道如何获取非组所有者的IP。因为它不是要求连接的设备,所以它没有WifiP2pInfo类。它甚至不知道组所有者的IP。如何从此设备向组所有者发送数据?
先感谢您。

你得到答案了吗?如果是的话,请分享一下,我需要它。 - Abhishek choudhary
1个回答

1

您可以获取双方的本地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";
    }
}

2
谢谢。当套接字连接时,我通过socket.getInetAddress()获取了IP地址。 - Tianlong Song
无法在三星Galaxy Grand 2上运行,我已经测试过了。不能通过这种方式获取IP地址。 - David

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接