Welcome To Golang By Example

Menu
  • Home
  • Blog
Menu

Get Hostname in Go (Golang)

Posted on April 13, 2023January 5, 2023 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
  • 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

    ©2023 Welcome To Golang By Example | Design: Web XP