sou*_*rar 14 networking android
有谁知道如何获得Android设备的公共IP地址?
我正在尝试运行服务器套接字(只是试验简单的p2p).
这需要通知本地和远程用户的公共IP.我找到了这个帖子如何从代码中获取设备的IP地址?其中包含指向如何获取IP 的文章(http://www.droidnova.com/get-the-ip-address-of-your-device,304.html)的链接.然而,这通过路由器连接时返回本地IP,我想获得实际的公共IP.
TIA
Bra*_*tie 13
只需访问http://automation.whatismyip.com/n09230945.asp并刮掉它?
whatismyip.com非常适合获取IP,尽管该网站要求您每5分钟只打一次.
2015年2月更新
WhatIsMyIp现在公开了一个可以使用的开发人员API.
从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();
}
Run Code Online (Sandbox Code Playgroud)
我用这个函数获取公网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;
}
}
Run Code Online (Sandbox Code Playgroud)
当然可以优化,我把它留给贡献他们解决方案的大师。
归档时间: |
|
查看次数: |
29255 次 |
最近记录: |