-
Notifications
You must be signed in to change notification settings - Fork 1
/
realip.go
46 lines (38 loc) · 1.12 KB
/
realip.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
package identity
import (
"net"
"net/http"
"strings"
"github.com/go-phorce/dolly/netutil"
)
// ClientIPFromRequest return client's real public IP address from http request headers.
func ClientIPFromRequest(r *http.Request) string {
// Fetch header value
xRealIP := r.Header.Get("X-Real-Ip")
xForwardedFor := r.Header.Get("X-Forwarded-For")
// If both empty, return IP from remote address
if xRealIP == "" && xForwardedFor == "" {
var remoteIP string
// If there are colon in remote address, remove the port number
// otherwise, return remote address as is
if strings.ContainsRune(r.RemoteAddr, ':') {
remoteIP, _, _ = net.SplitHostPort(r.RemoteAddr)
} else {
remoteIP = r.RemoteAddr
}
if remoteIP == "" {
remoteIP, _ = netutil.GetLocalIP()
}
return remoteIP
}
// Check list of IP in X-Forwarded-For and return the first global address
for _, address := range strings.Split(xForwardedFor, ",") {
address = strings.TrimSpace(address)
isPrivate, err := netutil.IsPrivateAddress(address)
if !isPrivate && err == nil {
return address
}
}
// If nothing succeed, return X-Real-IP
return xRealIP
}