How to get the hostname of the node in Go?

In Go lang, how to get the hostname of the node?

asked May 29 by dtivl (2,500 points)

1 Answer

In Go, you can use the os.Hostname() function to get the hostname of the node.

func Hostname() (name string, err error)

Hostname returns the host name reported by the kernel.

One example is as follows. The main.go source code:

package main

import (
	"fmt"
	"os"
)

func main() {
	name, err := os.Hostname()
	if err != nil {
		panic(err)
	}

	fmt.Println("hostname:", name)
}

Run it:

$ go run main.go
hostname: host001
answered May 29 by dtivl (2,500 points)

Please log in or register to answer this question.

Copyright © SysTutorials. User contributions licensed under cc-wiki with attribution required.
Hosted on Dreamhost

...