最近有个需求需要获取外网ip地址,找了很多资料都不行,要么是报错,于是自己整理了一下方法:
1.获取内网ip地址:
/** * 获取内网ip地址 * @param context * @return */ public static String getIntranetIPAddress(Context context) { NetworkInfo info = ((ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo(); if (info != null && info.isConnected()) { if (info.getType() == ConnectivityManager.TYPE_MOBILE) {//当前使用2G/3G/4G网络 try { for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) { NetworkInterface intf = en.nextElement(); for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) { InetAddress inetAddress = enumIpAddr.nextElement(); if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) { return inetAddress.getHostAddress(); } } } } catch (SocketException e) { e.printStackTrace(); } } else if (info.getType() == ConnectivityManager.TYPE_WIFI) {//当前使用无线网络 WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); WifiInfo wifiInfo = wifiManager.getConnectionInfo(); String ipAddress = intIP2StringIP(wifiInfo.getIpAddress());//得到IPV4地址 return ipAddress; } } else { //当前无网络连接,请在设置中打开网络 } return null; } /** * 将得到的int类型的IP转换为String类型 * * @param ip * @return */ public static String intIP2StringIP(int ip) { return (ip & 0xFF) + "." + ((ip >> 8) & 0xFF) + "." + ((ip >> 16) & 0xFF) + "." + (ip >> 24 & 0xFF); }
2.测试:
打印日志为:10.0.1.121
3.获取外网IP地址方法:
/** * 获取外网的IP(要访问Url,要放到后台线程里处理) * * @param @return * @return String * @throws * @Title: GetNetIp * @Description: */ public static String getNetExtraNetIpAddress() { URL infoUrl; InputStream inStream = null; String ipLine = ""; HttpURLConnection httpConnection = null; try { 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 sb = new StringBuilder(); String line; while ((line = reader.readLine()) != null){ sb.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(sb.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(); } } LogUtils.e("getNetIp", ipLine); return ipLine; }
4.测试:
打印日志为:61.49.113.194
5.测试了华为、小米手机,模拟器也测试了几款都能正常获取内外网IP地址,TV和盒子也能正常获取.