github.com/lulzWill/go-agent@v2.1.2+incompatible/internal/sysinfo/hostname_linux.go (about)

     1  package sysinfo
     2  
     3  import (
     4  	"os"
     5  	"syscall"
     6  )
     7  
     8  // Hostname returns the host name.
     9  func Hostname() (string, error) {
    10  	// Try the builtin API first, which is designed to match the output of
    11  	// /bin/hostname, and fallback to uname(2) if that fails to match the
    12  	// behavior of gethostname(2) as implemented by glibc. On Linux, all
    13  	// these method should result in the same value because sethostname(2)
    14  	// limits the hostname to 64 bytes, the same size of the nodename field
    15  	// returned by uname(2). Note that is correspondence is not true on
    16  	// other platforms.
    17  	//
    18  	// os.Hostname failures should be exceedingly rare, however some systems
    19  	// configure SELinux to deny read access to /proc/sys/kernel/hostname.
    20  	// Redhat's OpenShift platform for example. os.Hostname can also fail if
    21  	// some or all of /proc has been hidden via chroot(2) or manipulation of
    22  	// the current processes' filesystem namespace via the cgroups APIs.
    23  	// Docker is an example of a tool that can configure such an
    24  	// environment.
    25  	name, err := os.Hostname()
    26  	if err == nil {
    27  		return name, nil
    28  	}
    29  
    30  	var uts syscall.Utsname
    31  	if err2 := syscall.Uname(&uts); err2 != nil {
    32  		// The man page documents only one possible error for uname(2),
    33  		// suggesting that as long as the buffer given is valid, the
    34  		// call will never fail. Return the original error in the hope
    35  		// it provides more relevant information about why the hostname
    36  		// can't be retrieved.
    37  		return "", err
    38  	}
    39  
    40  	// Convert Nodename to a Go string.
    41  	buf := make([]byte, 0, len(uts.Nodename))
    42  	for _, c := range uts.Nodename {
    43  		if c == 0 {
    44  			break
    45  		}
    46  		buf = append(buf, byte(c))
    47  	}
    48  
    49  	return string(buf), nil
    50  }