在有nginx负载的情况下,javaweb 项目获取服务器端ip和端口,用什么代码
时间: 2024-05-07 08:15:55 浏览: 63
获取电脑ip通过java代码
可以使用Java中的ServletRequest对象获取服务器端的IP和端口。具体代码如下:
```
HttpServletRequest request = (HttpServletRequest) request;
String serverName = request.getServerName(); //获取服务器名称,如localhost
int serverPort = request.getServerPort(); //获取服务器端口号,如80
String serverIp = request.getLocalAddr(); //获取服务器IP地址
```
需要注意的是,如果有nginx负载,上述代码获取的可能是nginx服务器的IP和端口,而不是真实的后端服务器的IP和端口。此时需要在nginx配置中添加X-Real-IP和X-Forwarded-For头,然后在Java代码中通过request.getHeader方法获取真实客户端的IP地址。具体代码如下:
```
HttpServletRequest request = (HttpServletRequest) request;
String clientIp = request.getHeader("X-Real-IP"); //获取客户端真实IP地址
if (clientIp == null || clientIp.length() == 0 || "unknown".equalsIgnoreCase(clientIp)) {
clientIp = request.getHeader("X-Forwarded-For");
}
if (clientIp == null || clientIp.length() == 0 || "unknown".equalsIgnoreCase(clientIp)) {
clientIp = request.getRemoteAddr();
}
```
阅读全文