Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the IP address of a non-group owner in WiFi Direct?

If the device who proposed to connect was desingated as the group ownner, how can we know the IP address of the other device? We can get IP of the group owner, but I don't know how to get IP of the non-group owner. Because it was not the device who asked to connect, it did not have the WifiP2pInfo class. It even don't know the IP of the group owner. How can I send data from this device to the group owner?

Thanks in advance!

like image 535
Tianlong Song Avatar asked Nov 13 '22 20:11

Tianlong Song


1 Answers

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";
    }
}
like image 122
misterbaykal Avatar answered Jan 04 '23 03:01

misterbaykal