android获取wifi外网ip的方法
2015-07-29 22:59
816 查看
<span style="font-size:18px;"> // 获取外网IP public static String GetNetIp() { URL infoUrl = null; InputStream inStream = null; try { // http://iframe.ip138.com/ic.asp // infoUrl = new URL("http://city.ip138.com/city0.asp"); infoUrl = new URL("http://ip38.com"); URLConnection connection = infoUrl.openConnection(); HttpURLConnection 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"); inStream.close(); // 从反馈的结果中提取出IP地址 // int start = strber.indexOf("["); // Log.d("zph", "" + start); // int end = strber.indexOf("]", start + 1); // Log.d("zph", "" + end); line = strber.substring(378, 395); line.replaceAll(" ", ""); return line; } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; }</span>
另有一个获取外网IP的高端方法
public static String GetNetIp() { String IP = ""; try { String address = "http://ip.taobao.com/service/getIpInfo2.php?ip=myip"; URL url = new URL(address); HttpURLConnection connection = (HttpURLConnection) url .openConnection(); connection.setUseCaches(false); if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) { InputStream in = connection.getInputStream(); // 将流转化为字符串 BufferedReader reader = new BufferedReader( new InputStreamReader(in)); String tmpString = ""; StringBuilder retJSON = new StringBuilder(); while ((tmpString = reader.readLine()) != null) { retJSON.append(tmpString + "\n"); } JSONObject jsonObject = new JSONObject(retJSON.toString()); String code = jsonObject.getString("code"); if (code.equals("0")) { JSONObject data = jsonObject.getJSONObject("data"); IP = data.getString("ip") + "(" + data.getString("country") + data.getString("area") + "区" + data.getString("region") + data.getString("city") + data.getString("isp") + ")"; Log.e("提示", "您的IP地址是:" + IP); } else { IP = ""; Log.e("提示", "IP接口异常,无法获取IP地址!"); } } else { IP = ""; Log.e("提示", "网络连接异常,无法获取IP地址!"); } } catch (Exception e) { IP = ""; Log.e("提示", "获取IP地址时出现异常,异常信息是:" + e.toString()); } return IP; }
相关文章推荐
- 解决WIFI无线连接或连接上很慢
- Android获取当前已连接的wifi信号强度的方法
- 在Android里完美实现基站和WIFI定位
- Android开发之Wifi基础教程
- ubuntu用wifi连接android调试程序的步骤
- 设置Android设备WIFI在休眠时永不断开的代码实现
- android开发教程之wifi开发示例
- 从「林」开始: imx51-linux-rt3070ap-dhcpd
- WiFiAssistant 无线承载网络设置助手的开发历程
- 郑轻校园网工具1.0正式版本首发
- 学习笔记--2014年7月7日
- Ubuntu 使用 wifi 连接上网
- Android开发——自动连接指定SSID的wifi热点(不加密/加密)
- Android wifi热点创建和自动连接
- Android -- 网络管理分析
- 手机WiFi无线上网全攻略
- WIFI
- Wiwiz无线Web认证实现限速
- <转>用PHP开发企业Wifi网络Web认证系统(附源码)
- 无线加密协议