确定设备公共IP

时间:2011-06-10 14:46:25

标签: android networking

有谁知道如何获取Android设备的公共IP地址?

我正在尝试运行服务器套接字(只是试验简单的p2p)。

这需要通知本地和远程用户的公共IP。我找到了这个帖子How to get IP address of the device from code?,其中包含指向文章(http://www.droidnova.com/get-the-ip-address-of-your-device,304.html)的链接,该文章展示了如何获取IP。但是,当通过路由器连接时,这将返回本地IP,而我希望获得实际的公共IP。

TIA

13 个答案:

答案 0 :(得分:13)

只需访问http://automation.whatismyip.com/n09230945.asp并刮掉它?

whatismyip.com非常适合获取IP,但网站requests只能每5分钟点击一次。

2015年2月更新

WhatIsMyIp现在公开了您可以使用的developer API

答案 1 :(得分:8)

checkip.org解析公共IP地址(使用JSoup):

public static String getPublicIP() throws IOException
{
    Document doc = Jsoup.connect("http://www.checkip.org").get();
    return doc.getElementById("yourip").select("h1").first().select("span").text();
}

答案 2 :(得分:4)

要查找公共IP,您需要调用http://www.whatismyip.com/之类的外部服务,并将外部IP作为响应返回。

答案 3 :(得分:4)

在一般情况下,你不能。很可能,设备没有公共IP地址(或者至少不是可以打开连接的地址)。如果它通过NAT路由器连接,则它将没有。

http://touch.whatsmyip.org/这样的工具返回的IP地址将是NAT路由器的面向公众的地址,而不是设备的地址。

大多数家庭和企业网络都使用NAT路由器,许多移动运营商也是如此。

答案 4 :(得分:3)

这是我的方式。

我有DNS记录

ip4 IN A 91.123.123.123

ip6 IN AAAA 1234:1234:1234:1234 :: 1

然后我在启用PHP的网站上有一个PHP脚本。 (您需要调整此脚本)

< ?PHP
echo $_SERVER['REMOTE_ADDR'];? >

如果我拨打ip6.mydomain.com/ip/,我有IPv6公共IP。如果我打电话给ip4.mydomain.com/ip/,我有IPv4公共IP。

然后我有以下java类。

public class IPResolver {

private HttpClient client = null;

private final Context context;

public IPResolver(Context context) {
    this.context = context;
}

public String getIp4() {

    String ip4 = getPage("http://ip4.mysite.ch/scripts/ip");
    return ip4;
}

public String getIp6() {

    String ip6 = getPage("http://ip6.mysite.ch/scripts/ip");
    return ip6;
}

private String getPage(String url) {

    // Set params of the http client
    if (client == null) {
        HttpParams httpParameters = new BasicHttpParams();
        int timeoutConnection = 2000;
        HttpConnectionParams.setConnectionTimeout(httpParameters,
                timeoutConnection);
        int timeoutSocket = 2000;
        HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
        client = new DefaultHttpClient(httpParameters);

    }

    try {

        HttpGet request = new HttpGet(url);
        HttpResponse response = client.execute(request);

        String html = "";
        InputStream in = response.getEntity().getContent();
        BufferedReader reader = new BufferedReader(
                new InputStreamReader(in));
        StringBuilder str = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            str.append(line);
        }
        in.close();
        html = str.toString();
        return html.trim();
    } catch (Throwable t) {
        // t.printStackTrace();
    }
    return null;
}

}

答案 5 :(得分:3)

我使用此函数获取公共IP地址,首先检查是否存在连接,然后请求返回公共IP地址的请求

public static String getPublicIPAddress(Context context) {
    //final NetworkInfo info = NetworkUtils.getNetworkInfo(context);

    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    final NetworkInfo info = cm.getActiveNetworkInfo();

    RunnableFuture<String> futureRun = new FutureTask<>(new Callable<String>() {
        @Override
        public String call() throws Exception {
            if ((info != null && info.isAvailable()) && (info.isConnected())) {
                StringBuilder response = new StringBuilder();

                try {
                    HttpURLConnection urlConnection = (HttpURLConnection) (
                            new URL("http://checkip.amazonaws.com/").openConnection());
                    urlConnection.setRequestProperty("User-Agent", "Android-device");
                    //urlConnection.setRequestProperty("Connection", "close");
                    urlConnection.setReadTimeout(15000);
                    urlConnection.setConnectTimeout(15000);
                    urlConnection.setRequestMethod("GET");
                    urlConnection.setRequestProperty("Content-type", "application/json");
                    urlConnection.connect();

                    int responseCode = urlConnection.getResponseCode();

                    if (responseCode == HttpURLConnection.HTTP_OK) {

                        InputStream in = new BufferedInputStream(urlConnection.getInputStream());
                        BufferedReader reader = new BufferedReader(new InputStreamReader(in));

                        String line;
                        while ((line = reader.readLine()) != null) {
                            response.append(line);
                        }

                    }
                    urlConnection.disconnect();
                    return response.toString();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                //Log.w(TAG, "No network available INTERNET OFF!");
                return null;
            }
            return null;
        }
    });

    new Thread(futureRun).start();

    try {
        return futureRun.get();
    } catch (InterruptedException | ExecutionException e) {
        e.printStackTrace();
        return null;
    }

}

当然可以对其进行优化,我将其留给那些提供解决方案的大师。

答案 6 :(得分:2)

我只是对ipinfo.io/ip

进行HTTP GET

以下是实施:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.HttpURLConnection;

public class PublicIP {

    public static String get() {
        return PublicIP.get(false);
    }

    public static String get(boolean verbose) {
        String stringUrl = "https://ipinfo.io/ip";

        try {
            URL url = new URL(stringUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();

            conn.setRequestMethod("GET");

            if(verbose) {
                int responseCode = conn.getResponseCode();
                System.out.println("\nSending 'GET' request to URL : " + url);
                System.out.println("Response Code : " + responseCode);
            }

            StringBuffer response = new StringBuffer();
            BufferedReader in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String inputLine;

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();

            if(verbose) {
                //print result
                System.out.println("My Public IP address:" + response.toString());
            }
            return response.toString();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

    public static void main(String[] args) {
        System.out.println(PublicIP.get());
    }
}

答案 7 :(得分:2)

public class Test extends AsyncTask {

    @Override
    protected Object doInBackground(Object[] objects) {

        URL whatismyip = null;
        try {
            whatismyip = new URL("http://icanhazip.com/");


            try {
                BufferedReader in = new BufferedReader(new InputStreamReader(
                        whatismyip.openStream()));


                String ip = in.readLine(); //you get the IP as a String
                Log.i(TAG, "EXT IP: " + ip);
            } catch (IOException e) {
                e.printStackTrace();
            }

        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        return null;
    }

}

答案 8 :(得分:1)

这是 Eng.Fouad 答案的延续,这是通过从checkip.org解析公共IP地址(使用JSoup)::

方法(如果您收到以前方法的异常错误,则包含此内容):

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import java.io.IOException;
**********
public static String getPublicIp()
    {
        String myip="";

        try{
            Document doc = Jsoup.connect("http://www.checkip.org").get();
            myip = doc.getElementById("yourip").select("h1").first().select("span").text();
            }
        catch(IOException e){
            e.printStackTrace();
            }
        return myip;
        }

调用方法示例:

<your class name> wifiInfo = new <your class name>();
String myIP = wifiInfo.getPublicIp();

在build.gradle依赖项中编译以下库

compile 'org.jsoup:jsoup:1.9.2'

使用Java API Version 8编译JSoup,因此在build.gradle defaultConfig {}

中添加以下内容
jackOptions{
        enabled true
        }

并将编译选项更改为:

    compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
    }

最后但并非最不重要的是,在onCreate()方法下放置以下代码,因为默认情况下您不应该通过UI运行网络操作(通过服务或AsyncTask推荐)然后重建代码。 /强>

StrictMode.enableDefaults();

测试并使用Lolipop和Kitkat。

答案 9 :(得分:1)

使用public static String getPublicIP() { try { RestTemplate restTemplate = new RestTemplate(); return restTemplate.getForObject("http://checkip.amazonaws.com/", String.class).replace("\n",""); } catch ( Exception e ) { return ""; } } Amazon API,您可以轻松获取公共IP。

node test.js command 'value'\''s values'

答案 10 :(得分:1)

df["status"] = df["status"].apply(lambda x: mapping_dict["Professional Status Activity"].get(x.lower(),2))

并随时随地致电

 public class getIp extends AsyncTask<String, String, String> {
        String result;

        @Override
        protected String doInBackground(String... strings) {
            CustomHttpClient client = new CustomHttpClient();
            try {
                result = client.executeGet("http://checkip.amazonaws.com/");
            } catch (Exception e) {
                e.printStackTrace();
            }
            return result;
        }
    }

CustomHttpClient.java

try {
            ip = new getIp().execute().get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

答案 11 :(得分:0)

我使用FreeGeoIP,并接收IP-&gt; GEO。

http://freegeoip.net/json

与whatismyip相比的另一种解决方案

答案 12 :(得分:0)

这是一个没有限制或需要认证的api

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

URL url = null;
try {
    url = new URL("https://api.ipify.org");
    String ip = getUrlContent(url);
    Log.d("ip is", ip);
} catch (IOException e) {
    e.printStackTrace();
}

private String getUrlContent(URL u) throws IOException {
    java.net.URLConnection c = u.openConnection();
    c.setConnectTimeout(2000);
    c.setReadTimeout(2000);
    c.connect();
    try (InputStream in = c.getInputStream()) {
        BufferedInputStream bis = new BufferedInputStream(in);
        ByteArrayOutputStream buf = new ByteArrayOutputStream();
        int result = bis.read();
        while(result != -1) {
            byte b = (byte)result;
            buf.write(b);
            result = bis.read();
        }
        return buf.toString();
    }
}