-
Notifications
You must be signed in to change notification settings - Fork 0
/
util.go
80 lines (72 loc) · 1.36 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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package main
import (
"errors"
"net"
"os"
"strconv"
"strings"
)
func hostname() (string, error) {
hostname, err := os.Hostname()
if err != nil {
return hostname, err
}
if !strings.HasSuffix(hostname, ".local") {
hostname += ".local"
}
return hostname, nil
}
func hostip() (string, error) {
addrs, err := net.InterfaceAddrs()
if err != nil {
return "", err
}
for _, a := range addrs {
if ipnet, ok := a.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
if ipnet.IP.To4() != nil {
return ipnet.IP.String(), nil
}
}
}
return "", errors.New("no network ip was found")
}
func ipOfInterface(name string) (string, error) {
iface, err := net.InterfaceByName(name)
if err != nil {
return "", err
}
addrs, err := iface.Addrs()
if err != nil {
return "", err
}
for _, a := range addrs {
ipnet, ok := a.(*net.IPNet)
if !ok {
continue
}
if ipnet.IP.IsLoopback() && (iface.Flags&net.FlagLoopback) == 0 {
continue
}
if ipnet.IP.To4() == nil {
continue
}
return ipnet.IP.String(), nil
}
return "", errors.New("inteface " + name + " has no ip address")
}
func ipv4(host string) bool {
parts := strings.Split(host, ".")
if len(parts) < 4 {
return false
}
for _, x := range parts {
if i, err := strconv.Atoi(x); err == nil {
if i < 0 || i > 255 {
return false
}
} else {
return false
}
}
return true
}