-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathip.go
executable file
·46 lines (38 loc) · 883 Bytes
/
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
package dnet
import (
"fmt"
"net"
"net/http"
"strings"
)
// GetIP returns the IP address from the client request
func GetIP(r *http.Request) (ip string, err error) {
// get ip from the X-REAL-IP
ip = r.Header.Get("X-REAL-IP")
netIP := net.ParseIP(ip)
if netIP != nil {
return ip, nil
}
//get ip from the X-FORWARDED-FOR
ips := r.Header.Get("X-FORWARDED-FOR")
ipsSlice := strings.Split(ips, ",")
// parse the ip to check if the ip is assigned
for _, ip := range ipsSlice {
netIP = net.ParseIP(ip)
// return the ip address if ip is valid
if netIP != nil {
return ip, nil
}
}
// get ip address from the RemoteAddr
ip, _, err = net.SplitHostPort(r.RemoteAddr)
if err != nil {
return "", err
}
netIP = net.ParseIP(ip)
if netIP != nil {
return ip, nil
}
// if no valid ip found
return "", fmt.Errorf("[dnet] no valid IP Address found ")
}