mirror of
https://github.com/gin-gonic/gin.git
synced 2026-06-28 04:58:15 +08:00
fix: handle IPv6 brackets and port in X-Forwarded-For parsing
The validateHeader function failed to parse X-Forwarded-For values with: - IPv6 addresses in brackets: [240e:318:2f4a:de56::240] - Port numbers: 192.168.8.39:38792 - Both: [240e:318:2f4a:de56::240]:38792 Use net.SplitHostPort to properly handle all formats, falling back to bracket stripping for bare bracketed IPv6 addresses. Fixes #4572
This commit is contained in:
parent
ecd26c8835
commit
ec789274b1
11
gin.go
11
gin.go
@ -486,6 +486,17 @@ func (engine *Engine) validateHeader(header string) (clientIP string, valid bool
|
||||
items := strings.Split(header, ",")
|
||||
for i := len(items) - 1; i >= 0; i-- {
|
||||
ipStr := strings.TrimSpace(items[i])
|
||||
|
||||
// Handle IPv6 with brackets and/or port: [::1], [::1]:8080, 192.168.1.1:8080
|
||||
// net.SplitHostPort handles all these cases and strips brackets
|
||||
if host, _, err := net.SplitHostPort(ipStr); err == nil {
|
||||
ipStr = host
|
||||
} else {
|
||||
// No port present, just strip brackets if any (bare IPv6 like [::1])
|
||||
ipStr = strings.TrimPrefix(ipStr, "[")
|
||||
ipStr = strings.TrimSuffix(ipStr, "]")
|
||||
}
|
||||
|
||||
ip := net.ParseIP(ipStr)
|
||||
if ip == nil {
|
||||
break
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user