首页 > 代码库 > 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; }
Android 获取外网IP,实测有效
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。