Welcome To Golang By Example

Menu
  • Home
  • Blog
  • Contact Us
  • Support this website
Menu

Get Hostname in Go (Golang)

Posted on April 13, 2020January 5, 2021 by admin

Table of Contents

  • Overview
  • Code

Overview

‘os’ package of golang provides a Hostname function that can be used to get the hostname that is reported by the kernel
Below is the signature of this method. It returns an error if not able to successfully get the hostname

func Hostname() (name string, err error)

Let’s see a working code

Code

package main

import (
	"fmt"
	"os"
)

func main() {
	hostname, err := os.Hostname()
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
	fmt.Printf("Hostname: %s", hostname)
}

Output:

Hostname: 
  • go
  • golang
  • hostname
  • os
  • Follow @golangbyexample

    Popular Articles

    Golang Comprehensive Tutorial Series

    All Design Patterns in Go (Golang)

    Slice in golang

    Variables in Go (Golang) – Complete Guide

    OOP: Inheritance in GOLANG complete guide

    Using Context Package in GO (Golang) – Complete Guide

    All data types in Golang with examples

    Understanding time and date in Go (Golang) – Complete Guide

    ©2025 Welcome To Golang By Example | Design: Newspaperly WordPress Theme