-
Notifications
You must be signed in to change notification settings - Fork 283
/
hostname.go
67 lines (59 loc) · 1.31 KB
/
hostname.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
package registry
import (
"errors"
"fmt"
"net"
"os"
"strings"
)
func isFQDN(host string) bool {
return strings.Count(host, ".") > 1
}
func chooseIP(ips []net.IP) net.IP {
for _, ip := range ips {
if !ip.IsLoopback() && !ip.IsInterfaceLocalMulticast() && !ip.IsLinkLocalUnicast() && !ip.IsLinkLocalMulticast() {
return ip
}
}
return nil
}
// getViaLookup tries to lookup whether short hostname may be resolved into IP and back into a longer one
func getViaLookup(host string) (string, error) {
addrs, err := net.LookupIP(host)
if err != nil {
return "", err
}
if len(addrs) == 0 {
return "", errors.New("address lookup failed")
}
for _, addr := range addrs {
hosts, err := net.LookupAddr(addr.String())
if err != nil {
continue
}
for _, h := range hosts {
h = strings.TrimSuffix(h, ".")
if isFQDN(h) {
return h, nil
}
}
}
if ip := chooseIP(addrs); ip != nil {
return ip.String(), nil
}
return "", errors.New("lookup failed")
}
// getHostOrIP tries to fetch a publicly accessible IP address for the current host/container
func getHostOrIP() (string, error) {
host, err := os.Hostname()
if err != nil {
return "", fmt.Errorf("hostname: %w", err)
}
if isFQDN(host) {
return host, nil
}
if h, err := getViaLookup(host); err == nil {
return h, nil
}
return host, nil
}