Android 获取外网IP,实测有效
2023-09-11 14:18:37 时间
网上有很多获取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_activity实现一个简单的新建联系表
- Android API之android.widget.Filterable
- 《android开发艺术探索》读书笔记(十)--Android的消息机制
- Android开发学习---android下的数据持久化,保存数据到rom文件,android_data目录下文件访问的权限控制
- 【VLC-Android】vlc-android简例
- 【VLC-Android】Mac下编译vlc-android
- Android点亮解锁屏幕
- android: 平台版本对应api及占比统计(android studio 2022.1.1)
- Android studio中 android-support-v4报错问题
- 一个没有停止的android闹钟,一旦开始就要把歌唱完 .
- 在Eclipse添加Android兼容包( v4、v7 appcompat )
- Android Button去掉默认阴影
- Android 11.0 12.0SystemUI设置系统导航栏默认为系统手势导航
- Android 10.0 framework修改AlertDialog button样式
- Android 进入第三方app的某个Activity
- 【Android Gradle 插件】LintOptions 配置 ⑥ ( checkReleaseBuilds 属性配置 | disable 属性配置 | enable 属性配置 )
- 【Android 逆向】整体加固脱壳 ( DexClassLoader 加载 dex 流程分析 | 查找 DexFile 对应的C代码 | dalvik_system_DexFile.cpp 分析 )
- android获取ip命令
- 解决Android中No resource found that matches android:TextAppearance.Material.Widget.Button.Inverse问题
- Android Framework 保姆级开发学习路线,全套资料包开源分享
- android 输入法如何启动流程_Android输入法显示流程