Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

SplitHostPort is needed since Request.RemoteAddr has the host:port format #25501

Merged
merged 1 commit into from
May 22, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
10 changes: 8 additions & 2 deletions pkg/util/net/http.go
Original file line number Diff line number Diff line change
Expand Up @@ -153,8 +153,14 @@ func GetClientIP(req *http.Request) net.IP {
}

// Fallback to Remote Address in request, which will give the correct client IP when there is no proxy.
ip := net.ParseIP(req.RemoteAddr)
return ip
// Remote Address in Go's HTTP server is in the form host:port so we need to split that first.
host, _, err := net.SplitHostPort(req.RemoteAddr)
if err == nil {
return net.ParseIP(host)
}

// Fallback if Remote Address was just IP.
return net.ParseIP(req.RemoteAddr)
}

var defaultProxyFuncPointer = fmt.Sprintf("%p", http.ProxyFromEnvironment)
Expand Down
6 changes: 4 additions & 2 deletions pkg/util/net/http_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,8 @@ func TestGetClientIP(t *testing.T) {
},
{
Request: http.Request{
RemoteAddr: ipString,
// RemoteAddr is in the form host:port
RemoteAddr: ipString + ":1234",
},
ExpectedIP: ip,
},
Expand All @@ -90,6 +91,7 @@ func TestGetClientIP(t *testing.T) {
Header: map[string][]string{
"X-Forwarded-For": {invalidIPString},
},
// RemoteAddr is in the form host:port
RemoteAddr: ipString,
},
ExpectedIP: ip,
Expand All @@ -98,7 +100,7 @@ func TestGetClientIP(t *testing.T) {

for i, test := range testCases {
if a, e := GetClientIP(&test.Request), test.ExpectedIP; reflect.DeepEqual(e, a) != true {
t.Fatalf("test case %d failed. expected: %v, actual: %v", i+1, e, a)
t.Fatalf("test case %d failed. expected: %v, actual: %v", i, e, a)
}
}
}
Expand Down