-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathutils.go
57 lines (51 loc) · 1.12 KB
/
utils.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
package main
import (
"log/slog"
"net"
"time"
)
// Date returns the date part of a time.Time
func Date(tm time.Time) time.Time {
y, m, d := tm.Date()
return time.Date(y, m, d, 0, 0, 0, 0, time.Local)
}
// GetInterfacesAndIPs returns a map of network interfaces and their
// IP addresses. This function ignores all errors.
func GetInterfacesAndIPs() map[string][]string {
m := make(map[string][]string)
ifaces, err := net.Interfaces()
if err != nil {
slog.Error(
"failed to get network interfaces",
slog.String("error", err.Error()),
)
return m
}
for _, iface := range ifaces {
addrs, err := iface.Addrs()
if err != nil {
slog.Error(
"failed to get addresses of network interface",
slog.String("interfaceName", iface.Name),
slog.String("error", err.Error()),
)
continue
}
ips := make([]string, 0, len(addrs))
for _, addr := range addrs {
ipnet, ok := addr.(*net.IPNet)
if !ok || ipnet.IP.IsLoopback() {
continue
}
ip := ipnet.IP.To4()
if ip == nil {
continue
}
ips = append(ips, ip.String())
}
if len(ips) > 0 {
m[iface.Name] = ips
}
}
return m
}