From 668da512661be305ff9c102e643a89b75d86a1a2 Mon Sep 17 00:00:00 2001 From: Shirong Lu <73147033+happysnaker@users.noreply.github.com> Date: Sat, 4 Jul 2026 00:09:57 +0800 Subject: [PATCH] fix: handle bracketed IPv6 and port notation in X-Forwarded-For validateHeader now correctly handles non-standard X-Forwarded-For formats including: - [IPv6]:port (e.g., [::1]:38792) - IPv4:port (e.g., 192.168.1.1:38792) - [IPv6] (e.g., [::1]) These formats are produced by some reverse proxies like IIS ARR and certain cloud load balancers. Fixes #4572 --- gin.go | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/gin.go b/gin.go index 2e033bf3..75b37dd8 100644 --- a/gin.go +++ b/gin.go @@ -486,6 +486,14 @@ 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]:port or IPv4:port notation (e.g., [::1]:38792, 192.168.1.1:38792) + if host, _, err := net.SplitHostPort(ipStr); err == nil { + ipStr = host + } + // Strip brackets around bare IPv6 addresses (e.g., [::1] -> ::1) + if len(ipStr) > 0 && ipStr[0] == '[' { + ipStr = strings.Trim(ipStr, "[]") + } ip := net.ParseIP(ipStr) if ip == nil { break