forked from premendrasingh/beats
-
Notifications
You must be signed in to change notification settings - Fork 0
/
net.go
64 lines (57 loc) · 1.34 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
package common
import (
"fmt"
"net"
)
// LocalIPAddrs finds the IP addresses of the hosts on which
// the shipper currently runs on.
func LocalIPAddrs() ([]net.IP, error) {
var localIPAddrs []net.IP
ipaddrs, err := net.InterfaceAddrs()
if err != nil {
return nil, err
}
for _, addr := range ipaddrs {
var ip net.IP
ok := true
switch v := addr.(type) {
case *net.IPNet:
ip = v.IP
case *net.IPAddr:
ip = v.IP
default:
ok = false
}
if !ok {
continue
}
localIPAddrs = append(localIPAddrs, ip)
}
return localIPAddrs, nil
}
// LocalIPAddrsAsStrings finds the IP addresses of the hosts on which
// the shipper currently runs on and returns them as an array of
// strings.
func LocalIPAddrsAsStrings(includeLoopbacks bool) ([]string, error) {
var localIPAddrsStrings = []string{}
var err error
ipaddrs, err := LocalIPAddrs()
if err != nil {
return []string{}, err
}
for _, ipaddr := range ipaddrs {
if includeLoopbacks || !ipaddr.IsLoopback() {
localIPAddrsStrings = append(localIPAddrsStrings, ipaddr.String())
}
}
return localIPAddrsStrings, err
}
// IsLoopback check if a particular IP notation corresponds
// to a loopback interface.
func IsLoopback(ipStr string) (bool, error) {
ip := net.ParseIP(ipStr)
if ip == nil {
return false, fmt.Errorf("Wrong IP format %s", ipStr)
}
return ip.IsLoopback(), nil
}