java web在内网/局域网中访问,客户端主机ip获取

在外网:

public static String getIp(HttpServletRequest request){
    String ip = null;
        try{
        ip = request.getHeader("X-Real-IP");
            if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
            ip = request.getHeader("x-forwarded-for");
            }
            if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
                ip = request.getHeader("Proxy-Client-Ip");
            }
            if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
                ip = request.getHeader("WL-Proxy-Client-Ip");
            }
            if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
                ip = request.getRemoteAddr();
            }
            if(ip == null){
            ip = request.getLocalAddr();
            }
            if("0:0:0:0:0:0:0:1".equals(ip)){
                ip="127.0.0.1";
            }
        }catch(Exception ex){
            BaseLog.e(IpUtil.class, "getIp 获取Ip错误", ex);
        }
        return ip;
    }


在内网:

如果防火墙设置过高,上述request.getRemoteAddr();方法无法获取到客户端主机的ip地址。

解决方法:直接调取命令行,然后输入命令参数查询ip地址

如果存在虚拟主机:

Console cs = System.console();
    cs.readLine("ipconfig");

如果不存在:

Runtime rt = Runtime.getRuntime();
    Process pr = rt.exec("ipconfig");
    BufferedReader input = new BufferedReader(new InputStreamReader(pr.getInputStream(), "GBK"));  
    String line = null; 
 

while ((line = input.readLine()) != null) {

System.out.println(line);

}

input即为ipconfig查询的全部结果。


你可能感兴趣的:(javaEE学习笔记)