forked from torhve/infping
-
Notifications
You must be signed in to change notification settings - Fork 0
/
common.go
65 lines (55 loc) · 994 Bytes
/
common.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
64
65
// common stuff for infping and infhttp
// Copyright: 2018 Chris Luke
// License: MIT
package main
import (
"errors"
"fmt"
"net"
"os"
"strings"
)
func herr(err error) {
if err != nil {
fmt.Println(err)
os.Exit(1)
}
}
func perr(err error) {
if err != nil {
fmt.Println(err)
}
}
func lookupAddrFromIface(iface string, ipv6 bool) (net.IP, error) {
i, err := net.InterfaceByName(iface)
herr(err)
addrs, err := i.Addrs()
herr(err)
var ip net.IP
for _, addr := range addrs {
switch v := addr.(type) {
case *net.IPNet:
ip = v.IP
case *net.IPAddr:
ip = v.IP
}
addrstr := ip.String()
if ipv6 {
if strings.Contains(addrstr, ":") {
if strings.HasPrefix(addrstr, "f") {
// link local or something
continue
}
return ip, nil
} else {
// want ipv6, no ipv6 addr!
continue
}
} else {
return ip, nil
}
}
// no suitable address found
err = errors.New("no suitable IP address found on interface")
return ip, err
}