Android 获取外网IP,实测有效
生活随笔
收集整理的這篇文章主要介紹了
Android 获取外网IP,实测有效
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
網上有很多獲取IP的例子,不過都是獲取到的本地ip,還有的是因為走不通了,獲取到的ip為空,下面看實測獲取到外網IP的代碼,注意需要在線程里面執行
?
/*** 獲取外網的IP(要訪問Url,要放到后臺線程里處理)** @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;}?
轉載于:https://www.cnblogs.com/feijian/p/6601427.html
總結
以上是生活随笔為你收集整理的Android 获取外网IP,实测有效的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Vue学习之路---No.7(分享心得,
- 下一篇: 正则表达式,grep,sed,