hostname2/get_linux.go

43 lines
874 B
Go

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
}