-
Notifications
You must be signed in to change notification settings - Fork 0
/
util.go
63 lines (56 loc) · 1.07 KB
/
util.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
package netx
import (
"errors"
"net"
)
type IfacePred func(net.Interface) bool
func LocalIPs(ifacePred IfacePred) ([]net.IP, error) {
ifaces, err := net.Interfaces()
if err != nil {
return nil, err
}
ips := make([]net.IP, 0)
for _, iface := range ifaces {
addrs, err := iface.Addrs()
if err != nil {
continue
}
if ifacePred != nil && !ifacePred(iface) {
continue
}
for _, addr := range addrs {
var ip net.IP
switch v := addr.(type) {
case *net.IPNet:
ip = v.IP
case *net.IPAddr:
ip = v.IP
}
ips = append(ips, ip)
}
}
return ips, nil
}
func LocalIP(ifacePred IfacePred) (net.IP, error) {
ips, err := LocalIPs(ifacePred)
if err != nil {
return nil, err
}
if len(ips) == 0 {
return nil, errors.New("Not found IP")
}
return ips[0], nil
}
func LocalIPStr(ifacePred IfacePred, def string) string {
ip, err := LocalIP(ifacePred)
if err != nil {
return def
}
return ip.String()
}
func OnlyEth0(iface net.Interface) bool {
return iface.Name == "eth0"
}
func OnlyEth1(iface net.Interface) bool {
return iface.Name == "eth1"
}