forked from zalando/skipper
-
Notifications
You must be signed in to change notification settings - Fork 0
/
net.go
65 lines (58 loc) · 1.48 KB
/
net.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
package net
import (
"net"
"net/http"
"strings"
)
// strip port from addresses with hostname, ipv4 or ipv6
func stripPort(address string) string {
if h, _, err := net.SplitHostPort(address); err == nil {
return h
}
return address
}
func parse(addr string) net.IP {
if addr != "" {
res := net.ParseIP(stripPort(addr))
return res
}
return nil
}
// RemoteHost returns the remote address of the client. When the
// 'X-Forwarded-For' header is set, then it is used instead. This is
// how most often proxies behave. Wikipedia shows the format
// https://en.wikipedia.org/wiki/X-Forwarded-For#Format
//
// Example:
//
// X-Forwarded-For: client, proxy1, proxy2
func RemoteHost(r *http.Request) net.IP {
ffs := r.Header.Get("X-Forwarded-For")
ff := strings.Split(ffs, ",")[0]
if ffh := parse(ff); ffh != nil {
return ffh
}
return parse(r.RemoteAddr)
}
// RemoteHostFromLast returns the remote address of the client. When
// the 'X-Forwarded-For' header is set, then it is used instead. This
// is known to be true for AWS Application LoadBalancer. AWS docs
// https://docs.aws.amazon.com/elasticloadbalancing/latest/classic/x-forwarded-headers.html
//
// Example:
//
// X-Forwarded-For: ip-address-1, ip-address-2, client-ip-address
func RemoteHostFromLast(r *http.Request) net.IP {
a := r.Header["X-Forwarded-For"]
if a == nil {
return parse(r.RemoteAddr)
}
l := len(a) - 1
if l < 0 {
l = 0
}
if ffh := parse(a[l]); ffh != nil {
return ffh
}
return parse(r.RemoteAddr)
}