File: fqdn.go

package info (click to toggle)
golang-github-showmax-go-fqdn 0.0~git20160909.2501cdd-1
  • links: PTS, VCS
  • area: main
  • in suites: buster, buster-backports
  • size: 56 kB
  • sloc: makefile: 2
file content (37 lines) | stat: -rw-r--r-- 679 bytes parent folder | download
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
package fqdn

import (
	"net"
	"os"
	"strings"
)

// Get Fully Qualified Domain Name
// returns "unknown" or hostanme in case of error
func Get() string {
	hostname, err := os.Hostname()
	if err != nil {
		return "unknown"
	}

	addrs, err := net.LookupIP(hostname)
	if err != nil {
		return hostname
	}

	for _, addr := range addrs {
		if ipv4 := addr.To4(); ipv4 != nil {
			ip, err := ipv4.MarshalText()
			if err != nil {
				return hostname
			}
			hosts, err := net.LookupAddr(string(ip))
			if err != nil || len(hosts) == 0 {
				return hostname
			}
			fqdn := hosts[0]
			return strings.TrimSuffix(fqdn, ".") // return fqdn without trailing dot
		}
	}
	return hostname
}