-
Notifications
You must be signed in to change notification settings - Fork 1
/
ipaddress.go
48 lines (39 loc) · 843 Bytes
/
ipaddress.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
package main
import (
"fmt"
"net"
hierr "github.com/reconquest/hierr-go"
)
func getIP(netdev string, IPv4Flag bool) (string, error) {
ifaces, err := net.InterfaceByName(netdev)
if err != nil {
return "", hierr.Errorf(err, "can't get network interfaces")
}
addrs, err := ifaces.Addrs()
if err != nil {
return "", hierr.Errorf(err, "can't get addresses for interface")
}
var IP string
for _, a := range addrs {
ips, _, err := net.ParseCIDR(a.String())
if err != nil {
return "", hierr.Errorf(err, "can't parse cidr")
}
switch {
case IPv4Flag:
if ips.To4() != nil {
IP = ips.To4().String()
break
}
case !IPv4Flag:
if ips.To4() == nil {
IP = ips.To16().String()
break
}
}
}
if len(IP) == 0 {
return "", fmt.Errorf("can't found IP address on interface")
}
return IP, nil
}