-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathip.go
More file actions
93 lines (74 loc) · 1.68 KB
/
ip.go
File metadata and controls
93 lines (74 loc) · 1.68 KB
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
package utils
import (
"bytes"
"net"
"sync"
)
const (
UnknownIP = "UNKNOWN IP"
HeaderXForwardedFor = "X-Forwarded-For"
HeaderXRealIP = "X-Real-IP"
)
var (
ip = ""
ips = make([]string, 0, 5)
onceIP = &sync.Once{}
onceIPs = &sync.Once{}
)
type Peekable interface {
Peek(key string) []byte
}
// GetLocalIP Returns IP address of local machine, empty string if fails
func GetLocalIP() string {
onceIP.Do(func() {
addrs, err := net.InterfaceAddrs()
if err != nil {
ip = ""
return
}
for _, address := range addrs {
ipnet, ok := address.(*net.IPNet)
// check the address type and if it is not a loopback the display it
if ok && !ipnet.IP.IsLoopback() && ipnet.IP.To4() != nil {
ip = ipnet.IP.String()
break
}
}
})
return ip
}
// Returns strinngs slice of IP found on local machine
func GetLocalIPs() []string {
onceIPs.Do(func() {
addrs, err := net.InterfaceAddrs()
if err != nil {
ips = nil
return
}
for _, address := range addrs {
ipnet, ok := address.(*net.IPNet)
// check the address type and if it is not a loopback the display it
if ok && !ipnet.IP.IsLoopback() && ipnet.IP.To4() != nil {
ips = append(ips, ipnet.IP.String())
}
}
})
return ips
}
// RealIp - Extracts first ip address from Peekable interface seperated by coma
// Returns nil if no values are presemt
func RealIP(peekable Peekable) []byte {
ipHeader := peekable.Peek(HeaderXForwardedFor)
if len(ipHeader) == 0 {
ipHeader = peekable.Peek(HeaderXRealIP)
}
if len(ipHeader) == 0 {
return nil
}
firstIndex := bytes.IndexRune(ipHeader, ',')
ip := ipHeader
if firstIndex != -1 {
ip = ipHeader[:firstIndex]
}
return ip
}