summaryrefslogtreecommitdiff
path: root/get_linux.go
blob: e7cd6d0d69cb76d110073d85cf19cefb7e916d80 (plain)
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
package hostname

// functions to import and export the protobuf
// data to and from config files

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

func osGetHostname() (string, error) {
	host, err := os.Hostname()
	if err != nil {
		return host, fmt.Errorf("failed to get hostname: %w", err)
	}

	domain, err := getDomainName()
	if err != nil || domain == "" {
		return host, err
	}

	return fmt.Sprintf("%s.%s", host, domain), nil
}

// getDomainName executes the 'domainname' command and returns its output.
func getDomainName() (string, error) {
	cmd := exec.Command("domainname")
	var out bytes.Buffer
	cmd.Stdout = &out
	if err := cmd.Run(); err != nil {
		return "", fmt.Errorf("failed to execute 'domainname': %w", err)
	}
	domain := strings.TrimSpace(out.String())
	if domain == "(none)" {
		return "", ErrorDomainNameMisconfigured
	}

	return domain, nil
}