-
Notifications
You must be signed in to change notification settings - Fork 0
/
ip.go
34 lines (31 loc) · 776 Bytes
/
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
package util
import (
"errors"
"net"
)
// NoDefaultIP means 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
}