0

手机设备连接3G网络时,如何判断安卓设备的ip地址是否公开?

public static InetAddress getLocalIpAddress() {
    try {
        for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
            NetworkInterface intf = en.nextElement();
            for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
                InetAddress address = enumIpAddr.nextElement();
                return address;
            }
        }
    } catch (SocketException ex) {
        Log.e(DEBUG_TAG, ex.toString());
    }
    return null;
}
4

1 回答 1

0

写一个像这样的快速小网页:

<?php echo $_SERVER["REMOTE_ADDR"]; ?>

然后使用异步任务获取它:

import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import android.os.AsyncTask;

public class NetreadTask extends AsyncTask<String, Void, String> {
    protected String doInBackground(String... urls) {
        return netread(urls[0]);
    }

    public final String netread(String url) {
        try {
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpGet httpGet = new HttpGet(url);
            ResponseHandler<String> resHandler = new BasicResponseHandler();
            String page;
            page = httpClient.execute(httpGet, resHandler);
            return page;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
    }
}

像这样称呼它:

String publicip = new NetreadTask().exec([yourpage]).get();

然后比较两者。您通过上述方法获得的 ip 保证给您公共 ip 地址。

我知道这是一个老问题,但我希望它对某人有所帮助!

于 2013-06-25T17:31:49.077 回答