关于Java获取公网IP地址

本文介绍了在项目中如何获取服务器的公网IP和本地IP。对于需要通过白名单进行接口调用的情况,可以通过访问http://pv.sohu.com/cityjson?ie=utf-8来获取公网IP。代码示例展示了具体的实现过程,包括异常处理和日志记录。同时,也提供了获取本地IP的Java代码片段。
摘要由CSDN通过智能技术生成
  • 首先写这个只是做个笔记,下次直接需要使用,真是不想吐槽有些文章标题党,搜的就是如何查看公网IP 外网IP ,你们标题挂着也是获取公网IP、 外网IP ,写的是获取本地的IP ,好像有大病。

  • 做这个是因为项目可能要部署很多个服务器,因为有些接口只有在一个服务器有白名单才能调通,需要获取公网IP 做判断去转发需要用到如何查看自己公网的IP。

  1. 获取公网IP 外网IP

访问 http://pv.sohu.com/cityjson?ie=utf-8可以直接获取到自己的外网IP

		String ip = "http://pv.sohu.com/cityjson?ie=utf-8";
		String inputLine = "";
		String read = "";
		String toIp="";
		try {
			URL url = new URL(ip);
			HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
			BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
			while ((read = in.readLine()) != null) {
				inputLine += read;
			}
			String ObjJson=inputLine.substring(inputLine.indexOf("=")+1,inputLine.length()-1);
			JSONObject jsonObj= JSON.parseObject(ObjJson);
			toIp=jsonObj.getString("cip");
		} catch (Exception e) {
			toIp="";
			log.error("------------------异常信息{}",e);
		}
		log.info("-------------------------{}",toIp);
		if(Ip.equals(toIp)){
			return true;
		}
		return false;
  1. 本地IP
	try {
			InetAddress ip = Inet4Address.getLocalHost();
			System.out.println(ip.getHostAddress());
		} catch (UnknownHostException e) {
			e.printStackTrace();
		}
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

唐洋QuQ

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值