5

如果提议连接的设备被指定为组所有者,我们如何知道其他设备的 IP 地址?我们可以得到群主的IP,但我不知道如何获取非群主的IP。因为请求连接的不是设备,所以它没有 WifiP2pInfo 类。它甚至不知道群主的IP。如何从该设备向群组所有者发送数据?

提前致谢!

4

1 回答 1

1

You can fetch local IP addresses of both peers and than compare them with group owner IP. As you may already know you can easily get group owner IP with this line of code:

WifiP2pInfo.info.groupOwnerAddress.getHostAddress();

For local IP you can simply use this:

localIp = getDottedDecimalIP(getLocalIPAddress());

with the related methods below:

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";
    }
}
于 2012-11-14T19:22:14.420 回答