Android notes: Android devices get public IP

Today, I have a friend who wants to get the current ip of Android phone connected to the network and ask me how to do it. I think it's not easy. Tell him to judge the network environment first. If WiFi can be obtained through WiFi manager, if it is traffic (2G, 3G or 4G network), get getHostAddress() through NetworkInterface traversal. But they require to obtain the current ip of the external network instead of the LAN ip sent by the router. Generally, when our mobile phone is connected to the router, the ip assigned to us by the router is The LAN ip of the C segment forwarded by the router is 192.168.x.xx, but how can we obtain the real Internet ip we want?

Don't talk much and go straight to the code.

public class MainActivity extends Activity {

    private TextView tv;

    protected void onCreate(Bundle savedInstanceState) {
        tv = (TextView) findViewById(;
        new Thread(new Runnable() {
            public void run() {
                URL infoUrl = null;
                InputStream inStream = null;
                String line = "";
                try {
                    infoUrl = new URL("");
                    URLConnection connection = infoUrl.openConnection();
                    HttpURLConnection httpConnection = (HttpURLConnection) connection;
                    int responseCode = httpConnection.getResponseCode();
                    if (responseCode == HttpURLConnection.HTTP_OK) {
                        inStream = httpConnection.getInputStream();
                        BufferedReader reader = new BufferedReader(new InputStreamReader(inStream, "utf-8"));
                        StringBuilder strber = new StringBuilder();
                        while ((line = reader.readLine()) != null)
                            strber.append(line + "\n");
                        // Extract the IP address from the feedback result
                        int start = strber.indexOf("{");
                        int end = strber.indexOf("}");
                        String json = strber.substring(start, end + 1);
                        if (json != null) {
                            try {
                                JSONObject jsonObject = new JSONObject(json);
                                line = jsonObject.optString("cip");
                            } catch (JSONException e) {

                } catch (MalformedURLException e) {
                } catch (IOException e) {



This is the way. You can modify it according to your actual needs.

Keywords: network JSON Android Mobile

Added by jossejf on Wed, 01 Jan 2020 20:06:40 +0200