我想获取远程计算机中客户端的IP地址。我正在使用此代码:
public static String getClientIpAddr(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)) {
ip = request.getHeader("HTTP_CLIENT_IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_X_FORWARDED_FOR");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
return ip;
}
但它始终会返回IPv6
,有没有办法获得IPv4
?
答案 0 :(得分:0)
如果您获得IPv6地址,则使用IPv6。 IPv4和IPv6是不同的协议,客户端选择在两者都可用时使用哪个协议。
如果您需要客户端的IPv4地址,则可以通过不在DNS中公布IPv6地址来强制它们使用它。随着IPv6的部署越来越多,这将是个坏主意。支持两者都很好,因此最好使用IPv6来处理客户端。