forked from elastic/beats
-
Notifications
You must be signed in to change notification settings - Fork 1
/
net.go
42 lines (38 loc) · 1022 Bytes
/
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
package main
import (
"net"
)
func LocalIpAddrs() ([]net.IP, error) {
var localAddrs = []net.IP{}
addrs, err := net.InterfaceAddrs()
if err != nil {
return []net.IP{}, err
}
for _, addr := range addrs {
if ipnet, ok := addr.(*net.IPNet); ok {
localAddrs = append(localAddrs, ipnet.IP)
}
}
return localAddrs, nil
}
func LocalIpAddrsAsStrings(include_loopbacks bool) ([]string, error) {
var localAddrsStrings = []string{}
var err error
ipaddrs, err := LocalIpAddrs()
if err != nil {
return []string{}, err
}
for _, ipaddr := range ipaddrs {
if include_loopbacks || !ipaddr.IsLoopback() {
localAddrsStrings = append(localAddrsStrings, ipaddr.String())
}
}
return localAddrsStrings, err
}
func IsLoopback(ip_str string) (bool, error) {
ip := net.ParseIP(ip_str)
if ip == nil {
return false, MsgError("Wrong IP format %s", ip_str)
}
return ip.IsLoopback(), nil
}