Java获取本机公网IP方法汇总

  • Post author:
  • Post category:java




一、通过第三方IP查询平台曲线获取本机公网IP(最准确、不稳定)

原理:通过类似

ipip.net

站长工具,获取访问者设置IP信息,由于国内设置多级路由跳转,通过该方法获取的IP地址准确性十分的高(毕竟别人就是做这个事的。。)缺陷就是官方未提供外部接口,只能通过正则表达式对页面上IP所在的元素标签进行获取。

示例1如下(已失效,思路可以参考下):

  • 测试站长网址:

    http://ip.chinaz.com/
  • 元素标识:

    <dd class="fz24">171.88.45.2**</dd>

    ,标签内的171.88.45.2**即为本机公网IP

核心代码:

	/**
	*@Function
	*@Description 得到本机外网ip
	**/
	public static String getV4IP() {
		String ip = "";
		String chinaz = "http://ip.chinaz.com/";

		String inputLine = "";
		String read = "";
		try {
			URL url = new URL(chinaz);
			HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
			BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
			while ((read = in.readLine()) != null) {
				inputLine += read;
			}
			System.out.println(inputLine);

		} catch (Exception e) {
			e.printStackTrace();
		}
		//正则匹配标签,注意\\
		Pattern p = Pattern.compile("\\<dd class\\=\"fz24\">(.*?)\\<\\/dd>");
		Matcher m = p.matcher(inputLine);
		if(m.find()){
			ip = m.group(1);
		}
		return ip;
	}


补充

  • 关于获取页面上指定元素标签的方法:

    以Chrome浏览器为例,F12进行控制台,切换到

    Elements

    标签,点击元素选择器(即左上角鼠标图标或快捷键

    Ctrl+Shift+C

    )光标移到页面IP显示位置点击鼠标,控制台会自动定位到元素标签
  • 如果抛出异常:

    java.lang.NoClassDefFoundError: javax/servlet/http/HttpServletResponse

    ,手动导入Tomcat安装目录下servlet.jar包即可



参考

示例2(推荐):

通过sohu的站长工具获取ip

请求

http://pv.sohu.com/cityjson

时,会返回

var returnCitySN = {"cip": "182.139.65.178", "cid": "510000", "cname": "????"};

//由于返回的数据是json对象,需要转成map后取值即可
private static final ObjectMapper objectMapper = new ObjectMapper();
/**
	 * 格式化json返回Map<String, Object>
	 *
	 * @return
	 */
	public static Map<String, Object> json2Map(String json){
		Map map = Maps.newHashMap();

		try {
			map = objectMapper.readValue(json, new TypeReference<Map<String, Object>>() {});
		} catch (IOException e) {
			e.printStackTrace();
		}

		return map;
	}


getV4IP()

	/**
	*@Function
	*@Description 得到本机外网ip
	**/
	public static String getV4IP() {
		String ip = "";
		String sohu = "http://pv.sohu.com/cityjson";
		String inputLine = "";
		String read = "";
		try {
			URL url = new URL(sohu);
			HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
			BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
			while ((read = in.readLine()) != null) {
				inputLine += read;
			}
			//防止乱码
			inputLine = new String(inputLine.getBytes("ISO-8859-1"),"UTF-8");
			//提取json格式的对象
			inputLine = StrUtil.sub(inputLine,StrUtil.indexOf(inputLine,'{'),StrUtil.lastIndexOfIgnoreCase(inputLine,"}")+1);
			//System.out.println(inputLine);
			Map<String,Object> map = json2Map(inputLine);
			ip = map.get("cip")!=null?map.get("cip").toString():"";

		} catch (Exception e) {
			e.printStackTrace();
		}
		return ip;
	}



版权声明:本文为Robin_hc原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。