forked from elastic/beats
-
Notifications
You must be signed in to change notification settings - Fork 9
/
net.go
50 lines (46 loc) · 1.23 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
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 []net.IP{}, err
}
for _, ipaddr := range ipaddrs {
if ipnet, ok := ipaddr.(*net.IPNet); ok {
localIPAddrs = append(localIPAddrs, ipnet.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
}