Skip to content

Instantly share code, notes, and snippets.

@iamdeveloper-lopez
Created March 19, 2019 04:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iamdeveloper-lopez/b1b84f309fcf492dca20f1082f19ba7c to your computer and use it in GitHub Desktop.
Save iamdeveloper-lopez/b1b84f309fcf492dca20f1082f19ba7c to your computer and use it in GitHub Desktop.
Getting IP address in simple way.
import android.os.AsyncTask;
import android.util.Log;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class IPFinderTask extends AsyncTask<Void, Void, String> {
private static final String TAG = IPFinderTask.class.getSimpleName();
public static IPFinderTask newInstance() {
return new IPFinderTask();
}
@Override
protected String doInBackground(Void... voids) {
try {
URL url = new URL("https://api.ipify.org/?format=text");
HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();
httpConnection.setRequestMethod("GET");
InputStream inputStream = httpConnection.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String ip = bufferedReader.readLine();
Log.d(TAG, "IP : " + ip);
httpConnection.disconnect();
return ip;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment