Skip to content

Commit a45f07d

Browse files
authored
fix: resolve RealIP for bare RemoteAddr without port (#3054)
RealIP and LegacyIPExtractor discarded the address when net.SplitHostPort failed (e.g. bare IPv4/IPv6 without :port). Reuse extractIP so behavior matches ExtractIPDirect.
1 parent 79b4968 commit a45f07d

3 files changed

Lines changed: 15 additions & 5 deletions

File tree

context.go

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,6 @@ import (
1212
"io/fs"
1313
"log/slog"
1414
"mime/multipart"
15-
"net"
1615
"net/http"
1716
"net/url"
1817
"path"
@@ -252,8 +251,8 @@ func (c *Context) RealIP() string {
252251
}
253252
// req.RemoteAddr is the IP address of the remote end of the connection, which may be a proxy. It is populated by the
254253
// http.conn.readRequest() method and uses net.Conn.RemoteAddr().String() which we trust.
255-
ra, _, _ := net.SplitHostPort(c.request.RemoteAddr)
256-
return ra
254+
// Use extractIP so bare IPs (no host:port) still resolve, matching ExtractIPDirect.
255+
return extractIP(c.request)
257256
}
258257

259258
// Path returns the registered path for the handler.

context_test.go

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1350,6 +1350,18 @@ func TestContext_RealIP(t *testing.T) {
13501350
whenReq: &http.Request{RemoteAddr: "89.89.89.89:1654"},
13511351
expect: "89.89.89.89",
13521352
},
1353+
{
1354+
name: "ip from bare remote addr without port",
1355+
givenIPExtrator: nil,
1356+
whenReq: &http.Request{RemoteAddr: "89.89.89.89"},
1357+
expect: "89.89.89.89",
1358+
},
1359+
{
1360+
name: "ip from bare ipv6 remote addr without port",
1361+
givenIPExtrator: nil,
1362+
whenReq: &http.Request{RemoteAddr: "2001:db8::1"},
1363+
expect: "2001:db8::1",
1364+
},
13531365
{
13541366
name: "ip from ip extractor",
13551367
givenIPExtrator: ExtractIPFromRealIPHeader(TrustIPRange(ipv6ForRemoteAddrExternalRange)),

ip.go

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -304,6 +304,5 @@ func legacyIPExtractor(req *http.Request) string {
304304
ip = strings.TrimSuffix(ip, "]")
305305
return ip
306306
}
307-
ra, _, _ := net.SplitHostPort(req.RemoteAddr)
308-
return ra
307+
return extractIP(req)
309308
}

0 commit comments

Comments
 (0)