Getting WiFi Direct IP address of my device

Talib picture Talib · Nov 28, 2013 · Viewed 10.8k times · Source

I am trying to get the ip address of my device but all in vain and no success. I've tried

public String getP2PIpAddr() {
       WifiManager wifiManager = (WifiManager) getSystemService(WIFI_P2P_SERVICE);
       WifiInfo wifiInfo = wifiManager.getConnectionInfo();
       int ip = wifiInfo.getIpAddress();

       String ipString = String.format(
       "%d.%d.%d.%d",
       (ip & 0xff),
       (ip >> 8 & 0xff),
       (ip >> 16 & 0xff),
       (ip >> 24 & 0xff));

       return ipString;
    }

but its giving me 0.0.0.0 and no other method is working too..Help !!

Answer

Budius picture Budius · Dec 6, 2013

Just as reference: I'm the developer of the WiFi-Shoot (a direct file transfer app via WiFi Direct).

Unfortunately, there's no way to get your own IP address, and the general principle of operation is slightly different:

  • All the operations will be made with the WiFiP2PManager
  • call initialize to get a Channel, all other operations needs this channel.
  • after you discoverPeers and connect to one of them
  • you can requestGroupInfo that will tell you if that device is the group owner and what is the group owner IP address. So non-owners can connect to the owner using the supplied address and the owner will listen to connections.
  • you can also requestPeers that will give you a list of all connected peers. That includes MAC addresses and names.

The call Context.getSystemService(Context.WIFI_P2P_SERVICE) will give you a WiFiP2PManager.

And yes, you'll need a bunch of WiFI permission such as ACCESS_WIFI_STATE, CHANGE_WIFI_STATE among others.