46 lines
2.2 KiB
Java
46 lines
2.2 KiB
Java
package net.gepafin.tendermanagement.util;
|
|
|
|
import jakarta.servlet.http.HttpServletRequest;
|
|
|
|
import java.util.regex.Pattern;
|
|
|
|
public class IpAddressUtils {
|
|
|
|
private static final Pattern IPV4_PATTERN = Pattern.compile("^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$");
|
|
|
|
private static final Pattern IPV6_PATTERN = Pattern.compile(
|
|
"([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|" + "([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|" + "([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|" + "([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|" + ":((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|" + "::(ffff(:0{1,4}){0,1}:){0,1}(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3,3}" + "([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])|([0-9a-fA-F]{1,4}:){1,4}:" + "(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3,3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])");
|
|
|
|
public static String getClientIp(HttpServletRequest request) {
|
|
|
|
String ipAddress = null;
|
|
|
|
String[] headers = { "X-Forwarded-For", "X-Real-IP", "Proxy-Client-IP", "WL-Proxy-Client-IP", "HTTP_CLIENT_IP", "HTTP_X_FORWARDED_FOR" };
|
|
|
|
for (String header : headers) {
|
|
ipAddress = request.getHeader(header);
|
|
if (ipAddress != null && !ipAddress.isEmpty() && !"unknown".equalsIgnoreCase(ipAddress)) {
|
|
ipAddress = ipAddress.split(",")[0].trim();
|
|
break;
|
|
}
|
|
}
|
|
if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) {
|
|
ipAddress = request.getRemoteAddr();
|
|
}
|
|
if ("0:0:0:0:0:0:0:1".equals(ipAddress) || "127.0.0.1".equals(ipAddress)) {
|
|
ipAddress = "127.0.0.1";
|
|
}
|
|
if (isValidIpAddress(ipAddress)) {
|
|
return ipAddress;
|
|
} else {
|
|
return "Invalid IP";
|
|
}
|
|
}
|
|
|
|
private static boolean isValidIpAddress(String ipAddress) {
|
|
|
|
return IPV4_PATTERN.matcher(ipAddress).matches() || IPV6_PATTERN.matcher(ipAddress).matches();
|
|
}
|
|
}
|
|
|