Java获取本机ip和服务器ip

一、获取服务器IP

 1 String addr = InetAddress.getLocalHost().getHostAddress();//获得本机IP  

 

二、获取客户端本机IP

复制代码
复制代码
 1 String remoteAddr = request.getRemoteAddr();  
 2 String forwarded = request.getHeader("X-Forwarded-For");  
 3 String realIp = request.getHeader("X-Real-IP");  
 4 String ip = null;  
 5 if (realIp == null) {  
 6     if (forwarded == null) {  
 7         ip = remoteAddr;  
 8     } else {  
 9         ip = remoteAddr + "/" + forwarded.split(",")[0];  
10     }  
11 } else {  
12     if (realIp.equals(forwarded)) {  
13         ip = realIp;  
14     } else {  
15         if(forwarded != null){  
16             forwarded = forwarded.split(",")[0];  
17         }  
18         ip = realIp + "/" + forwarded;  
19     }  
20 }  
复制代码
posted @ 2020-01-14 16:43  星朝  阅读(2391)  评论(0编辑  收藏  举报