Определить устройство публичного ip - PullRequest
14 голосов
/ 10 июня 2011

Кто-нибудь знает, как я могу получить публичный IP-адрес устройства Android?

Я пытаюсь запустить серверный сокет (просто экспериментирую с простым p2p).

Это требует информирования локальных и удаленных пользователей друг о друге по общему IP. Я нашел эту тему Как получить IP-адрес устройства из кода? , который содержит ссылку на статью (http://www.droidnova.com/get-the-ip-address-of-your-device,304.html), в которой показано, как получить IP-адрес. при подключении через маршрутизатор, и я хотел бы получить реальный публичный IP вместо этого.

1011 * ТИА *

Ответы [ 13 ]

13 голосов
/ 10 июня 2011

Просто посетите http://automation.whatismyip.com/n09230945.asp и очистите его?

whatismyip.com идеально подходит для получения IP, хотя сайт запрашивает , вы нажимаете его только один раз каждые 5 минут.

ОБНОВЛЕНИЕ ФЕВРАЛЬ 2015

WhatIsMyIp теперь предоставляет API разработчика , который вы можете использовать.

8 голосов
/ 28 мая 2013

Анализ публичного IP-адреса с checkip.org (Использование 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();
}
5 голосов
/ 26 августа 2015
private class ExternalIP extends AsyncTask<Void, Void, String> {

    protected String doInBackground(Void... urls) {
        String ip = "Empty";

        try {
            HttpClient httpclient = new DefaultHttpClient();
            HttpGet httpget = new HttpGet("http://wtfismyip.com/text");
            HttpResponse response;

            response = httpclient.execute(httpget);

            HttpEntity entity = response.getEntity();
            if (entity != null) {
                long len = entity.getContentLength();
                if (len != -1 && len < 1024) {
                    String str = EntityUtils.toString(entity);
                    ip = str.replace("\n", "");
                } else {
                    ip = "Response too long or error.";
                }
            } else {
                ip = "Null:" + response.getStatusLine().toString();
            }

        } catch (Exception e) {
            ip = "Error";
        }

        return ip;
    }

    protected void onPostExecute(String result) {

        // External IP 
        Log.d("ExternalIP", result);
    }
}
4 голосов
/ 10 июня 2011

В общем случае вы не можете.Вполне возможно, что устройство не имеет общедоступного IP-адреса (или, по крайней мере, ни одного, к которому вы можете открыть соединение).Если он подключается через маршрутизатор NAT, он не будет иметь его.

IP-адрес, возвращаемый инструментом, подобным http://touch.whatsmyip.org/, будет общедоступным адресом маршрутизатора NAT, а не устройства..

Большинство домашних и корпоративных сетей используют маршрутизаторы NAT, как и многие операторы мобильной связи.

4 голосов
/ 10 июня 2011

Чтобы найти общедоступный IP-адрес, необходимо вызвать внешнюю службу, например http://www.whatismyip.com/, и получить внешний IP-адрес в ответ.

3 голосов
/ 08 мая 2017

Я использую эту функцию для получения общедоступного 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;
    }

}

Конечно, его можно оптимизировать, я оставляю его длямастера, которые вносят свои решения.

3 голосов
/ 21 марта 2014

Вот мой способ, которым я это делаю.

У меня есть записи DNS

ip4 IN 91.123.123.123

ip6 INAAAA 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;
}

}
2 голосов
/ 05 июня 2017
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;
    }

}
2 голосов
/ 26 февраля 2017

Я просто делаю HTTP GET для ipinfo.io/ip

Вот реализация:

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());
    }
}
1 голос
/ 04 июля 2017
 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;
        }
    }

и звоните куда угодно

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

CustomHttpClient.java

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.conn.params.ConnPerRouteBean;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.BufferedHttpEntity;
import org.apache.http.impl.auth.BasicScheme;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
public class CustomHttpClient {
    private static HttpClient custHttpClient;
    public static final int MAX_TOTAL_CONNECTIONS = 1000;
    public static final int MAX_CONNECTIONS_PER_ROUTE = 1500;
    public static final int TIMEOUT_CONNECT = 150000;
    public static final int TIMEOUT_READ = 150000;
    public static HttpClient getHttpClient() {
    if (custHttpClient == null) {
            SchemeRegistry schemeRegistry = new SchemeRegistry();
            schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
            schemeRegistry.register(new Scheme("https",SSLSocketFactory.getSocketFactory(), 443));
            HttpParams connManagerParams = new BasicHttpParams();
            ConnManagerParams.setMaxTotalConnections(connManagerParams, MAX_TOTAL_CONNECTIONS);
            ConnManagerParams.setMaxConnectionsPerRoute(connManagerParams, new ConnPerRouteBean(MAX_CONNECTIONS_PER_ROUTE));
            HttpConnectionParams.setConnectionTimeout(connManagerParams, TIMEOUT_CONNECT);
            HttpConnectionParams.setSoTimeout(connManagerParams, TIMEOUT_READ);
            ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(new BasicHttpParams(), schemeRegistry);
            custHttpClient = new DefaultHttpClient(cm, null);
            HttpParams para = custHttpClient.getParams();
            HttpConnectionParams.setConnectionTimeout(para, (30 * 10000));
            HttpConnectionParams.setSoTimeout(para, (30 * 10000));
            ConnManagerParams.setTimeout(para, (30 * 10000));
        }
        return custHttpClient;
    }
    public static String executePost(String urlPostFix,ArrayList<NameValuePair> postedValues)
    throws Exception {
        String url = urlPostFix;
        BufferedReader in = null;
        try {
            System.setProperty("http.keepAlive", "false");
            HttpClient client = getHttpClient();
            HttpPost request = new HttpPost(url);
            request.setHeader("Accept", "application/json");
            request.setHeader("Content-Type", "application/x-www-form-urlencoded");
            UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postedValues);
            formEntity.setContentType("application/json");
            request.setEntity(formEntity);
            HttpResponse response = client.execute(request);
            in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            StringBuffer sb = new StringBuffer("");
            String line = "";
            String NL = System.getProperty("line.separator");
            while ((line = in.readLine()) != null) {
                sb.append(line + NL);
            }
            in.close();
            String result = sb.toString();
            return result;
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                }
            }
        }
    }
    public static String executeGet(String urlPostFix)
            throws Exception {
                String url = urlPostFix;
                BufferedReader in = null;
                try {
                    HttpClient client = getHttpClient();
                    HttpGet request = new HttpGet( url);
                    request.setHeader("Accept", "application/json");
                    request.setHeader("Content-Type", "application/x-www-form-urlencoded");
                    HttpResponse response = client.execute(request);
                    in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
                    StringBuffer sb = new StringBuffer("");
                    String line = "";
                    String NL = System.getProperty("line.separator");
                    while ((line = in.readLine()) != null) {
                        sb.append(line + NL);
                    }
                    in.close();
                    String result = sb.toString();
                    return result;
                } finally {
                    if (in != null) {
                        try {
                            in.close();
                        } catch (IOException e) {
                        }
                    }
                }
            }
    public static Bitmap executeImageGet(String urlPostFix)
            throws Exception {
                String url = urlPostFix;
                InputStream in = null;
                try {
                    HttpClient client = getHttpClient();
                    HttpGet request = new HttpGet(url);
                    HttpResponse response = client.execute(request);
                    HttpEntity entity = response.getEntity();
                    BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity);
                    in = bufHttpEntity.getContent();
                    Bitmap bitmap = BitmapFactory.decodeStream(in);
                    in.close();
                    return bitmap;
                } finally {
                    if (in != null) {
                        try {
                            in.close();
                        } catch (IOException e) {
                        }
                }
                }
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...