forked from openshift/origin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ip.go
61 lines (56 loc) · 1.28 KB
/
ip.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
package util
import (
"errors"
"net"
)
// ErrorNoDefaultIP is returned when no suitable non-loopback address can be found.
var ErrorNoDefaultIP = errors.New("no suitable IP address")
// DefaultLocalIP4 returns an IPv4 address that this host can be reached
// on. Will return NoDefaultIP if no suitable address can be found.
func DefaultLocalIP4() (net.IP, error) {
devices, err := net.Interfaces()
if err != nil {
return nil, err
}
for _, dev := range devices {
if (dev.Flags&net.FlagUp != 0) && (dev.Flags&net.FlagLoopback == 0) {
addrs, err := dev.Addrs()
if err != nil {
continue
}
for i := range addrs {
if ip, ok := addrs[i].(*net.IPNet); ok {
if ip.IP.To4() != nil {
return ip.IP, nil
}
}
}
}
}
return nil, ErrorNoDefaultIP
}
// AllLocalIP4 returns all the IPv4 addresses that this host can be reached
// on.
func AllLocalIP4() ([]net.IP, error) {
devices, err := net.Interfaces()
if err != nil {
return nil, err
}
ret := []net.IP{}
for _, dev := range devices {
if dev.Flags&net.FlagUp != 0 {
addrs, err := dev.Addrs()
if err != nil {
continue
}
for i := range addrs {
if ip, ok := addrs[i].(*net.IPNet); ok {
if ip.IP.To4() != nil {
ret = append(ret, ip.IP)
}
}
}
}
}
return ret, nil
}