-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathextnet.go
87 lines (80 loc) · 1.96 KB
/
extnet.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
81
82
83
84
85
86
87
package main
import (
"fmt"
"net"
"strings"
)
// IsExternalInterface uses a string prefix list to weed out known internal interface names
func IsExternalInterface(ifname string) bool {
switch {
case strings.HasPrefix(ifname, "docker"):
return false
case strings.HasPrefix(ifname, "lxdbr"):
return false
default:
return true
}
}
func IsIPv4(address string) bool {
return strings.Count(address, ":") < 2
}
func IsIPv6(address string) bool {
return strings.Count(address, ":") >= 2
}
// ListExternalIPs returns a list of IP addresses on externally-reachable interfaces
func ListExternalIPs() ([]net.IP, error) {
var ips []net.IP
ifaces, err := net.Interfaces()
if err != nil {
return nil, fmt.Errorf("failed to enumerate network interfaces: %v", err)
}
for _, i := range ifaces {
if !IsExternalInterface(i.Name) {
log.Debugf("skipping internal interface %s", i.Name)
continue
}
addrs, err := i.Addrs()
if err != nil {
return nil, fmt.Errorf("failed to enumerate network addresses: %v", err)
}
for _, addr := range addrs {
var ip net.IP
switch v := addr.(type) {
case *net.IPNet:
ip = v.IP
case *net.IPAddr:
ip = v.IP
default:
continue
}
if ip.IsGlobalUnicast() {
ips = append(ips, ip)
}
}
}
return ips, nil
}
// findExternalAddr attempt to find a reachable external IP address for the system
func findExternalAddr() (string, error) {
// Discover local (listener) IP address
// Prefer IPv4 addresses
// If multiple are found default to the first
var listenAddr string
ips, err := ListExternalIPs()
if err != nil {
return "", fmt.Errorf("unable to list external IP addresses: %v", err)
}
for _, ip := range ips {
if IsIPv4(ip.String()) {
listenAddr = ip.String()
}
}
if listenAddr == "" {
// No IPv4 addresses found, choose the first IPv6 address
if len(ips) == 0 {
return "", fmt.Errorf("no valid external IP addresses found")
}
listenAddr = ips[0].String()
}
return listenAddr, nil
}