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

一、通过第三方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;
	}
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值