Android笔记:Android设备获取公网IP

  今天有个朋友要获取Android手机当前连入网络的ip,问我怎么做,我一想这还不简单。告诉他先判断是什么网络环境,如果是WiFi可以通过WifiManager获取到,如果是流量(2G、3G或者4G网)就通过NetworkInterface遍历获取getHostAddress()获得,但是他们要求获取不是路由器发出的局域网ip,而是当前的外网ip,一般我们手机连接路由器,路由器分给我们的ip都是路由器转发的C网段的局域网ip,也就是192.168.x.xx  这样的网段,但是我们想要的真实的外网ip怎么获取呢?

话不多说直接上代码。

public class MainActivity extends Activity {

    private TextView tv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tv = (TextView) findViewById(R.id.tv);
        new Thread(new Runnable() {
            @Override
            public void run() {
                URL infoUrl = null;
                InputStream inStream = null;
                String line = "";
                try {
                    infoUrl = new URL("http://pv.sohu.com/cityjson?ie=utf-8");
                    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");
                        inStream.close();
                        // 从反馈的结果中提取出IP地址
                        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) {
                                e.printStackTrace();
                            }

                        }
                        tv.setText("ip===="+line);
                    }
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                tv.setText("ip===="+line);
            }
        }).start();

    }

}

这就是方法了,大家可再根据自己的实际需要,进行修改。

你可能感兴趣的:(Android)