栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

关于Java获取公网IP地址

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

关于Java获取公网IP地址

  • 首先写这个只是做个笔记,下次直接需要使用,真是不想吐槽有些文章标题党,搜的就是如何查看公网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();
		}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/270199.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号