Refactored the GetIpddressFromRequest function to support ipv4 as well as ipv6 addresses (#3496)

This commit is contained in:
Aziz Rmadi
2024-01-03 13:07:11 -06:00
committed by GitHub
parent 468e32a2f0
commit bc1f66c858
2 changed files with 84 additions and 23 deletions

View File

@@ -23,24 +23,20 @@ func GenerateClientIDFromRequest(req *http.Request) string {
// GetIPAddressFromRequest returns the IP address from a http request.
func GetIPAddressFromRequest(req *http.Request) string {
ipAddressString := req.RemoteAddr
xForwardedFor := req.Header.Get("X-FORWARDED-FOR")
if xForwardedFor != "" {
clientIpString := strings.Split(xForwardedFor, ", ")[0]
// If the IP has a prefix of ::ffff: then it's an IPv4 address.
// Strip the prefix so we can parse it as an IPv4 address.
clientIpString = strings.TrimPrefix(clientIpString, "::ffff:")
if strings.Contains(clientIpString, ":") {
ip, _, err := net.SplitHostPort(clientIpString)
if err != nil {
log.Errorln(err)
return ""
}
return ip
}
return clientIpString
ipAddressString = strings.Split(xForwardedFor, ", ")[0]
}
if !strings.Contains(ipAddressString, ":") {
return ipAddressString
}
if isIPv6(ipAddressString) && !strings.Contains(ipAddressString, "[") {
return ipAddressString
}
ip, _, err := net.SplitHostPort(ipAddressString)
if err != nil {
log.Errorln(err)
@@ -49,3 +45,7 @@ func GetIPAddressFromRequest(req *http.Request) string {
return ip
}
func isIPv6(address string) bool {
return strings.Count(address, ":") >= 2
}