/
util.go
61 lines (54 loc) · 1.01 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
package srd
import (
"errors"
"net"
)
// GetLocalIP get the IP address of the current system
// physical or virtual machine
func GetLocalIP() (string, error) {
ip, err := externalIP()
return ip.String(), err
}
func externalIP() (net.IP, error) {
iFaces, err := net.Interfaces()
if err != nil {
return nil, err
}
for _, item := range iFaces {
if item.Flags&net.FlagUp == 0 {
continue // interface down
}
if item.Flags&net.FlagLoopback != 0 {
continue // loop back interface
}
addrs, err := item.Addrs()
if err != nil {
return nil, err
}
for _, addr := range addrs {
ip := getIpFromAddr(addr)
if ip == nil {
continue
}
return ip, nil
}
}
return nil, errors.New("get ip address error")
}
func getIpFromAddr(addr net.Addr) net.IP {
var ip net.IP
switch v := addr.(type) {
case *net.IPNet:
ip = v.IP
case *net.IPAddr:
ip = v.IP
}
if ip == nil || ip.IsLoopback() {
return nil
}
ip = ip.To4()
if ip == nil {
return nil // not an ipv4 address
}
return ip
}