diff --git a/context.go b/context.go index b784c14b..c885cf1b 100644 --- a/context.go +++ b/context.go @@ -8,6 +8,7 @@ import ( "errors" "io" "math" + "net" "net/http" "strings" "time" @@ -291,7 +292,10 @@ func (c *Context) ClientIP() string { return clientIP } } - return strings.TrimSpace(c.Request.RemoteAddr) + if ip, _, err := net.SplitHostPort(strings.TrimSpace(c.Request.RemoteAddr)); err == nil { + return ip + } + return "" } // ContentType returns the Content-Type header of the request. diff --git a/context_test.go b/context_test.go index 169768b6..c8dfa333 100644 --- a/context_test.go +++ b/context_test.go @@ -520,7 +520,7 @@ func TestContextClientIP(t *testing.T) { c.Request.Header.Set("X-Real-IP", " 10.10.10.10 ") c.Request.Header.Set("X-Forwarded-For", " 20.20.20.20, 30.30.30.30") - c.Request.RemoteAddr = " 40.40.40.40 " + c.Request.RemoteAddr = " 40.40.40.40:42123 " assert.Equal(t, c.ClientIP(), "10.10.10.10")