golang

Hostname Retrieval in Go (get hostname)

There is a very high chance that you are familiar with what a hostname is in the context of computing. But in case you are not, a hostname is a unique label that is assigned to a given device in a computer network.

The role of a hostname is to help identify and locate the devices on the network which makes it a critical feature in network related tasks.

In this tutorial, we will learn all the various methods and techniques that we can use to programmatically retrieve the hostname of a system using the Go programming language.

Why Would I Need the Hostname?

Although it may differ depending on your needs and application requirements, some common use cases where you might need to retrieve the hostname of a machine include the following:

  1. Configuration management – One common use case of hostnames is when configuring the services and applications on a remote machine.
  2. Logging and monitoring – Another use case is when you need to include the hostname identifier in the logs for identity.
  3. Network programming – If you need to perform any form of network programming, you are going to need the hostname. For example, establishing connections or resolving IP addresses and more.

With that out of the way, let us learn the various methods and techniques of fetching the hostname of a machine.

Method 1: Using the OS Package

The most command and straightforward method of retrieving the hostname in Go is using the OS package. The OS package contains low-level implementations of interacting with the hostname which includes basic networking tasks.

Consider the following example code that demonstrates how to use the OS package to fetch the hostname of a given system:

package main
import (
    "fmt"
    "os"
)
func main() {
    hostname, err := os.Hostname()
    if err != nil {
        fmt.Println("Error:", err)
        return
    }
    fmt.Println("Hostname:", hostname)
}

In this example, we start by importing the fmt and OS packages to work with OS-related functions.

We then call the os.Hostname() function to retrieve the hostname of the current machine. We also ensure to handle the potential errors that might occur when attempting to retrieve the hostname.

Finally, we can print the hostname as follows:

Hostname: anonymous.local

One advantage of using the OS package is that it is very straightforward and works on nearly any system that has a Go compiler installed.

Method 2: Using the Syscall Package (Win)

The second method that we can use to fetch the hostname in Go is using the syscall package. This method provides more control and can be useful when we need to perform the low-level system interactions.

An example on how to use the syscall package to fetch the hostname is as follows:

package main
import (
    "fmt"
    "syscall"
    "unsafe"
)
func main() {
    var buf [1024]byte
    size := uint32(len(buf))
    err := syscall.GetComputerName((*uint16)(unsafe.Pointer(&buf[0])), &size)
    if err != nil {
        fmt.Println("Error:", err)
        return
    }
    hostname := syscall.UTF16ToString(buf[:])
    fmt.Println("Hostname:", hostname)
}

This should return the hostname of the current machine.

The main drawback of this technique is that it is only Windows specific.

Method 3: Using an External Command

We can dial back the process of using the system packages and just use Go to call an external command which can help to retrieve the hostname and capture the output.

This is possible using the OS/exec package. An example code implementation is as follows:

package main
import (
    "fmt"
    "os/exec"
)
func main() {
    cmd := exec.Command("hostname")
    hostname, err := cmd.Output()
    if err != nil {
        fmt.Println("Error:", err)
        return
    }
    fmt.Println("Hostname:", string(hostname))
}

In this example, we create a variable called “cmd” which contains the hostname command. This command allows us to get the hostname of the local machine.

We then use the cmd.Output() method to execute the command and capture the resulting output.

Method 4: Using Psutil

If you are not familiar with psutil or process and system utilities, it is a free and open-source cross-platform library to retrieve the information on running processes and system utilization. This includes resources such as CPU, memory, disks, networks, sensors, and more.

By default, psutil is implemented in Python. But luckily, we have a version that is ported in Go which we can use to retrieve the hostname and other awesome tasks.

https://github.com/shirou/gopsutil

Start by installing the package using the “go get” command as follows:

$ go get github.com/shirou/gopsutil/host

Once installed, we can create the following code to retrieve the hostname of the system:

package main
import (
    "fmt"

    "github.com/shirou/gopsutil/host"
)
func main() {
    info, err := host.Info()
    if err != nil {
        fmt.Println("Error:", err)
        return
    }
    fmt.Println("Hostname:", info.Hostname)
}

This example uses the host.Info() method to gather the information about the host. Finally, we retrieve the hostname value and print it to the console.

Conclusion

In this tutorial, we learned all about the hostname feature in Go. We also covered all the methods that you can use to retrieve the hostname of the local machine.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list