File: fqdn-unix.go

package info (click to toggle)
golang-github-hlandau-goutils 0.0~git20160722.0.0cdb66a-3
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, buster
  • size: 160 kB
  • sloc: makefile: 2
file content (42 lines) | stat: -rw-r--r-- 690 bytes parent folder | download | duplicates (4)
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
// +build !windows,!plan9

package os

import (
	"bytes"
	"os"
	"os/exec"
	"regexp"
	"strings"
)

var reValidHostname = regexp.MustCompile(`^([0-9a-zA-Z-]+\.)[0-9a-zA-Z-]+$`)

func machineFQDN() (string, error) {
	hn, err := os.Hostname()
	if err != nil {
		return "", err
	}

	hn = strings.TrimSuffix(hn, ".")
	n := strings.Count(hn, ".")
	if n > 0 {
		return hn, nil
	}

	buf := bytes.Buffer{}
	cmd := exec.Command("hostname", "-f")
	cmd.Stdout = &buf

	err = cmd.Run()
	if err != nil {
		return hn, err
	}

	fqdn := strings.TrimSuffix(strings.TrimSpace(buf.String()), ".")
	if !reValidHostname.MatchString(fqdn) || strings.Count(fqdn, ".") < n {
		return hn, nil
	}

	return fqdn, nil
}