Android 获取外网IP,实测有效
生活随笔
收集整理的這篇文章主要介紹了
Android 获取外网IP,实测有效
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
網(wǎng)上有很多獲取IP的例子,不過(guò)都是獲取到的本地ip,還有的是因?yàn)樽卟煌?#xff0c;獲取到的ip為空,下面看實(shí)測(cè)獲取到外網(wǎng)IP的代碼,注意需要在線程里面執(zhí)行
?
/*** 獲取外網(wǎng)的IP(要訪問(wèn)Url,要放到后臺(tái)線程里處理)** @param @return* @return String* @throws* @Title: GetNetIp* @Description:*/public static String getNetIp() {URL infoUrl = null;InputStream inStream = null;String ipLine = "";HttpURLConnection httpConnection = null;try { // infoUrl = new URL("http://ip168.com/");infoUrl = new URL("http://pv.sohu.com/cityjson?ie=utf-8");URLConnection connection = infoUrl.openConnection();httpConnection = (HttpURLConnection) connection;int responseCode = httpConnection.getResponseCode();if (responseCode == HttpURLConnection.HTTP_OK) {inStream = httpConnection.getInputStream();BufferedReader reader = new BufferedReader(new InputStreamReader(inStream, "utf-8"));StringBuilder strber = new StringBuilder();String line = null;while ((line = reader.readLine()) != null){strber.append(line + "\n");}Pattern pattern = Pattern.compile("((?:(?:25[0-5]|2[0-4]\\d|((1\\d{2})|([1-9]?\\d)))\\.){3}(?:25[0-5]|2[0-4]\\d|((1\\d{2})|([1-9]?\\d))))");Matcher matcher = pattern.matcher(strber.toString());if (matcher.find()) {ipLine = matcher.group();}}} catch (MalformedURLException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {try {inStream.close();httpConnection.disconnect();} catch (IOException e) {e.printStackTrace();} catch (Exception ex) {ex.printStackTrace();}}Log.e("getNetIp", ipLine);return ipLine;}?
轉(zhuǎn)載于:https://www.cnblogs.com/feijian/p/6601427.html
總結(jié)
以上是生活随笔為你收集整理的Android 获取外网IP,实测有效的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: Vue学习之路---No.7(分享心得,
- 下一篇: Android架构分析之Android消