一、获取客户端ip的方法
//传入request对象,获得客户端ip
//注意,本地不行,本地会获取到0:0:0:0:0:0:0:1;服务器上是正常的
public static String getIpAddress(HttpServletRequest request) {
String 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)) {
//本地会获取到0:0:0:0:0:0:0:1
ip = request.getRemoteAddr();
}
if (ip.contains(",")) {
return ip.split(",")[0];
} else {
return ip;
}
}
二、获取服务器ip的方法
public static String getServerIP() {
String ip = null;
try {
//获取当前服务器ip
ip = InetAddress.getLocalHost().getHostAddress();
} catch (UnknownHostException e) {
LOG.error("获取当前服务器ip报错", e);
}
return ip;
}
三、其它备注
1.可以用RestTemplate
发送http请求文章来源地址https://www.toymoban.com/news/detail-503234.html
import org.springframework.web.client.RestTemplate;
RestTemplate restTemplate = new RestTemplate();
//这个是发送get请求,然后把返回报文转为string类型
String htmlXml = restTemplate.getForObject("www.baidu.com", String.class);
文章来源:https://www.toymoban.com/news/detail-503234.html
到了这里,关于Java后台获取客户端ip与服务器ip的方法的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!