-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathip.go
69 lines (60 loc) · 1.37 KB
/
ip.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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package userip
import (
"net"
"net/http"
"strings"
)
var (
cidrs []*net.IPNet
stringCIDRs = [...]string{"127.0.0.1/8", "10.0.0.0/8", "169.254.0.0/16",
"172.16.0.0/12", "192.168.0.0/16", "::1/128", "fc00::/7"}
)
func init() {
cidrs = make([]*net.IPNet, 0, len(cidrs))
for _, cidr := range stringCIDRs {
_, netCIDR, err := net.ParseCIDR(cidr)
if err != nil {
panic(err)
}
cidrs = append(cidrs, netCIDR)
}
}
// isLocal returns true if an IP should be considered local.
func isLocal(addr string) bool {
a := net.ParseIP(addr)
for _, cidr := range cidrs {
if cidr.Contains(a) {
return true
}
}
return false
}
// remoteAddr returns the IP portion of the RemoteAddr of the
// passed request, discarding any port.
func remoteAddr(r *http.Request) string {
addr := strings.TrimSpace(r.RemoteAddr)
lastColon := strings.LastIndex(addr, ":")
if lastColon == -1 {
return addr
}
return addr[:lastColon]
}
// Get returns a best guess at the IP a request came from.
func Get(r *http.Request) string {
realIP := r.Header.Get("X-Real-Ip")
forwardedFor := r.Header.Get("X-Forwarded-For")
if len(realIP) == 0 && len(forwardedFor) == 0 {
return remoteAddr(r)
}
for _, addr := range strings.Split(forwardedFor, ", ") {
addr = strings.TrimSpace(addr)
if len(addr) == 0 {
continue
}
if isLocal(addr) {
continue
}
return addr
}
return realIP
}