9

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 !!

Jared
  • 1,449
  • 2
  • 19
  • 40
Talib
  • 1,134
  • 5
  • 31
  • 58

7 Answers7

12

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.

Budius
  • 39,391
  • 16
  • 102
  • 144
  • it means you have worked in android P2P ,I have few questions, will you please give me your email address or facebook address, If you wanna help? – Talib Dec 10 '13 at 12:06
  • requestGroupInfo doesn't give you an IP Address – trampster Aug 02 '16 at 22:33
  • when a non owner connects to the owner, the owner can get the address of the connection and can use it or send it to the non owner – xuiqzy Mar 08 '20 at 16:02
7

send out the peer's local ip address (starting with 192.168.x.x) to the group owner. After this "handshake", which doesn't really take time, it's all good to go. Did not find any other way to get the peer's ip addresses, the only information provided by GroupListener/PeerListener/... is the mac address.

kapil thadani
  • 1,425
  • 14
  • 26
  • 4
    please explain it further. – user1850484 May 24 '15 at 20:14
  • 2
    This does not answer the question -- OP wants to know how to get own IP address not how to notify a GO of an already known IP address. The point is that we don't know where to get the 192.168.x.x from! – CodingLumis Jan 05 '18 at 13:05
4
public static String getIpAddress() {
    try {
        List<NetworkInterface> interfaces = Collections
                .list(NetworkInterface.getNetworkInterfaces());
        /*
         * for (NetworkInterface networkInterface : interfaces) { Log.v(TAG,
         * "interface name " + networkInterface.getName() + "mac = " +
         * getMACAddress(networkInterface.getName())); }
         */

        for (NetworkInterface intf : interfaces) {
            if (!getMACAddress(intf.getName()).equalsIgnoreCase(
                    Globals.thisDeviceAddress)) {
                // Log.v(TAG, "ignore the interface " + intf.getName());
                // continue;
            }
            if (!intf.getName().contains("p2p"))
                continue;

            Log.v(TAG,
                    intf.getName() + "   " + getMACAddress(intf.getName()));

            List<InetAddress> addrs = Collections.list(intf
                    .getInetAddresses());

            for (InetAddress addr : addrs) {
                // Log.v(TAG, "inside");

                if (!addr.isLoopbackAddress()) {
                    // Log.v(TAG, "isnt loopback");
                    String sAddr = addr.getHostAddress().toUpperCase();
                    Log.v(TAG, "ip=" + sAddr);

                    boolean isIPv4 = InetAddressUtils.isIPv4Address(sAddr);

                    if (isIPv4) {
                        if (sAddr.contains("192.168.49.")) {
                            Log.v(TAG, "ip = " + sAddr);
                            return sAddr;
                        }
                    }

                }

            }
        }

    } catch (Exception ex) {
        Log.v(TAG, "error in parsing");
    } // for now eat exceptions
    Log.v(TAG, "returning empty ip address");
    return "";
}

public static String getMACAddress(String interfaceName) {
        try {
            List<NetworkInterface> interfaces = Collections
                    .list(NetworkInterface.getNetworkInterfaces());

            for (NetworkInterface intf : interfaces) {
                if (interfaceName != null) {
                    if (!intf.getName().equalsIgnoreCase(interfaceName))
                        continue;
                }
                byte[] mac = intf.getHardwareAddress();
                if (mac == null)
                    return "";
                StringBuilder buf = new StringBuilder();
                for (int idx = 0; idx < mac.length; idx++)
                    buf.append(String.format("%02X:", mac[idx]));
                if (buf.length() > 0)
                    buf.deleteCharAt(buf.length() - 1);
                return buf.toString();
            }
        } catch (Exception ex) {
        } // for now eat exceptions
        return "";
        /*
         * try { // this is so Linux hack return
         * loadFileAsString("/sys/class/net/" +interfaceName +
         * "/address").toUpperCase().trim(); } catch (IOException ex) { return
         * null; }
         */
    }
Dipendra
  • 1,547
  • 19
  • 33
  • In API level 23, InetAddressUtils is deprecated. So check (inetAddress instanceof Inet4Address) instead InetAddressUtils.isIPv4Address(sAddr) – Khushbu Shah Apr 07 '16 at 09:52
0

Do you have permissions on the WiFi settings attached to your Android program manifest? At least ACCESS_WIFI_STATE is needed [1]. If that is not enough, probably ACCESS_NETWORK_STATE is also needed [2]. I did not find anything bad on your code, so trying to play with Manifest would be my suggestion.

The first link I have as source has in the accepted answer also INTERNET permission, so that your program can also contact somewhere to ask for connection and thus IP. That would be the next permission to try, if the two first don't work.

You asked about official or credible sources, these are from the credible ones. Every peace of information is voted up on Stackoverflow at least once, and that if something says that these stuff have made it at least for someone.

My sources:

[1] How to get IP address of the device from code?

[2] Android WifiManager getConnectionInfo requires CHANGE_WIFI_STATE?

Community
  • 1
  • 1
mico
  • 12,730
  • 12
  • 59
  • 99
0

If you are trying to get IP address of other device connected to WiFi network

try {
            Address = InetAddress.getLocalHost();
        } catch (UnknownHostException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } 

        System.out.println(Address);

Getting Internet IP address i.e live IP address

String myUrl = "http://api.externalip.net/ip";
        HttpClient httpClient = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(myUrl);

        try{
            HttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity ht = httpResponse.getEntity();
            BufferedHttpEntity buf = new BufferedHttpEntity(ht);
            InputStream is = buf.getContent();
            BufferedReader r = new BufferedReader(new InputStreamReader(is));
            StringBuilder total = new StringBuilder();
            String ipaddress = r.readLine();
            Toast.makeText(getApplicationContext(),"Live IP : " + ipaddress, Toast.LENGTH_LONG).show();
        }catch(Exception e){
            e.printStackTrace();
        }

For more deeper knowledge and other native methods fallow link

http://developer.android.com/guide/topics/connectivity/wifip2p.html

AndroidHacker
  • 3,596
  • 1
  • 25
  • 45
0

Firstly, check manifest file for permissions:

<uses-permission
    android:required="true"
    android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission
    android:required="true"
    android:name="android.permission.CHANGE_WIFI_STATE"/>
<uses-permission
    android:required="true"
    android:name="android.permission.INTERNET"/>

Then, define what's IP looking for. If you want to broadcast that IP for purpose beyond the service discovering, find it by using WIFI_SERVICE. If you are curious about the ip address of your service broadcasting, NsdServiceInfo instance has getHost() method.

pinxue
  • 1,736
  • 12
  • 17
-1

Use this code

WifiManager wifiMgr = (WifiManager) getSystemService(WIFI_SERVICE);
WifiInfo wifiInfo = wifiMgr.getConnectionInfo();
int ip = wifiInfo.getIpAddress();
String ipAddress = Formatter.formatIpAddress(ip); 

And add the permission to your manifest.

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
souvickcse
  • 7,742
  • 5
  • 37
  • 64
  • this code will provide wifi ip address from wifi router. I am looking for a code to get wifi-direct ip address. – user1850484 May 24 '15 at 19:07