Skip to content

Commit

Permalink
Fix #56 by using net.SplitHostPort.
Browse files Browse the repository at this point in the history
  • Loading branch information
didip committed Nov 18, 2017
1 parent 7753cc2 commit f2c85b5
Show file tree
Hide file tree
Showing 2 changed files with 3 additions and 15 deletions.
12 changes: 3 additions & 9 deletions libstring/libstring.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
package libstring

import (
"net"
"net/http"
"strings"
)
Expand All @@ -16,22 +17,15 @@ func StringInSlice(sliceString []string, needle string) bool {
return false
}

func ipAddrFromRemoteAddr(s string) string {
idx := strings.LastIndex(s, ":")
if idx == -1 {
return s
}
return s[:idx]
}

// RemoteIP finds IP Address given http.Request struct.
func RemoteIP(ipLookups []string, forwardedForIndexFromBehind int, r *http.Request) string {
realIP := r.Header.Get("X-Real-IP")
forwardedFor := r.Header.Get("X-Forwarded-For")

for _, lookup := range ipLookups {
if lookup == "RemoteAddr" {
return ipAddrFromRemoteAddr(r.RemoteAddr)
ip, _, _ := net.SplitHostPort(r.RemoteAddr)
return ip
}
if lookup == "X-Forwarded-For" && forwardedFor != "" {
// X-Forwarded-For is potentially a list of addresses separated with ","
Expand Down
6 changes: 0 additions & 6 deletions libstring/libstring_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,6 @@ func TestStringInSlice(t *testing.T) {
}
}

func TestIPAddrFromRemoteAddr(t *testing.T) {
if ipAddrFromRemoteAddr("127.0.0.1:8989") != "127.0.0.1" {
t.Errorf("ipAddrFromRemoteAddr did not chop the port number correctly.")
}
}

func TestRemoteIPDefault(t *testing.T) {
ipLookups := []string{"RemoteAddr", "X-Real-IP"}
ipv6 := "2601:7:1c82:4097:59a0:a80b:2841:b8c8"
Expand Down

1 comment on commit f2c85b5

@benguild
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That's not going to work. I'll update the issue.

Please sign in to comment.