ChitranjanThakur
ChitranjanThakur

Reputation: 91

How to capture the IP address of Android Application end user

--> IP address of Android Application end user

I have searched allot over internet about how to capture the IP ADDRESS of user who is actually using my ANDROID APPLICATION, but did not get the correct code which will work for me.

I am developing this android app on Eclipse.

on most of the forums i get this link which is not reachable at all: http://www.droidnova.com/get-the-ip-address-of-your-device,304.html

Need your support guys.

Thanks

Upvotes: 2

Views: 4224

Answers (3)

user529543
user529543

Reputation:

  1. try to open a connection to http://www.whatismyip.com and fetch the result.
  2. Make a HTTP POST ( or GET) to your app host and check there from which IP is coming the request.
  3. use SDK.

Edit: based on comment: that is the server side role to get the client IP, not the Android job. Here is a sample how can you do it with PHP: $_SERVER['REMOTE_ADDR']

Upvotes: 1

Igo Coelho
Igo Coelho

Reputation: 47

You can try the following code.

  public String 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()) {
             String ip = Formatter.formatIpAddress(inetAddress.hashCode());
             return ip;
           }
         }
      }
    } catch (SocketException ex) {
      // 
    }
    return null;
  }

Don't forget to add the following permission in order to allow your application to open network sockets:

 <uses-permission android:name="android.permission.INTERNET" /> 

Upvotes: 3

Naskov
Naskov

Reputation: 4169

Or instead of requesting the IP from the Server, you can tell your phone to send the IP.

You can get the IP adress with the following code.

public String 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()) {
                        return inetAddress.getHostAddress().toString();
                    }
                }
            }
        } catch (SocketException ex) {
            Log.e(tag, ex.toString());
        }
        return "";
    }

Upvotes: 0

Related Questions