-
首先写这个只是做个笔记,下次直接需要使用,真是不想吐槽有些文章标题党,搜的就是如何查看公网IP 外网IP ,你们标题挂着也是获取公网IP、 外网IP ,写的是获取本地的IP ,好像有大病。
-
做这个是因为项目可能要部署很多个服务器,因为有些接口只有在一个服务器有白名单才能调通,需要获取公网IP 做判断去转发需要用到如何查看自己公网的IP。
- 获取公网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;
- 本地IP
try {
InetAddress ip = Inet4Address.getLocalHost();
System.out.println(ip.getHostAddress());
} catch (UnknownHostException e) {
e.printStackTrace();
}