如何在Android和Java中获取设备的公共IP地址

时间:2018-10-12 11:59:36

标签: java android

如何在android中获取设备的公共IP地址。

请在这里找到我的代码。我正在获取设备的IP地址。但是我如何获得公共IP地址。

请帮助我

import java.util.Enumeration;

public class GetDeviceIp
{
  public GetDeviceIp() {}

  public static String getIpAddress()
  {
    try {
      Enumeration<java.net.NetworkInterface> en = 
        java.net.NetworkInterface.getNetworkInterfaces(); 
        Enumeration<java.net.InetAddress> enumIpAddr;
        for (; en.hasMoreElements(); enumIpAddr.hasMoreElements())
      {
        java.net.NetworkInterface intf = (java.net.NetworkInterface)en.nextElement();
        enumIpAddr = intf.getInetAddresses();continue;
        java.net.InetAddress inetAddress = (java.net.InetAddress)enumIpAddr.nextElement();
        if ((!inetAddress.isLoopbackAddress()) && 
          ((inetAddress instanceof java.net.Inet4Address))) {
          return inetAddress.getHostAddress();
        }
      }
    }
    catch (java.net.SocketException ex) {
      ex.printStackTrace();
      return null;
    }

  }
}

1 个答案:

答案 0 :(得分:0)

最简单的方法是创建http请求,该请求将从返回它的服务器获取公共IP。我使用了http://whatismyip.akamai.com/,因为它不需要任何解析,而且可能不会比这更简单。

对于代码,您需要创建另一个线程,该线程将发送http请求,但无法从主线程发送。提出的解决方案缺少超时,它不是多线程的好例子,可以实现。

public static String getPublicIPAddress(){
    String value = null;
    ExecutorService es = Executors.newSingleThreadExecutor();
    Future<String> result = es.submit(new Callable<String>() {
        public String call() throws Exception {
            try {
                URL url = new URL("http://whatismyip.akamai.com/");
                HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
                try {
                    InputStream in = new BufferedInputStream(urlConnection.getInputStream());
                    BufferedReader r = new BufferedReader(new InputStreamReader(in));
                    StringBuilder total = new StringBuilder();
                    String line;
                    while ((line = r.readLine()) != null) {
                        total.append(line).append('\n');
                    }
                    urlConnection.disconnect();
                    return total.toString();
                }finally {
                    urlConnection.disconnect();
                }
            }catch (IOException e){
                Log.e("Public IP: ",e.getMessage());
            }
            return null;
        }
    });
    try {
        value = result.get();
    } catch (Exception e) {
        // failed
    }
    es.shutdown();
    return value;
}