Created
March 19, 2019 04:26
-
-
Save iamdeveloper-lopez/b1b84f309fcf492dca20f1082f19ba7c to your computer and use it in GitHub Desktop.
Getting IP address in simple way.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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