Golang: How to know IP Address and Hostname

Sometimes you want to know the hostname and IP address of the machine you are running the program on.  We can get the hostname using the OS package.

For IP address we can use the Net package. You can read all IP addresses using InterfaceAddrs, you need to filter out the loopback address to get real IP. 

package main

import (
	"fmt"
	"net"
	"os"
)

func main() {
	//Reading the hostname using OS package.
	hostname, err := os.Hostname()
	if err != nil {
		fmt.Println("Hostname: ", hostname)
	}
	
	//Reading IP Address 
	addrs, err := net.InterfaceAddrs()
	if err == nil {
		for _, a := range addrs {
			if ipnet, ok := a.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
				if ipnet.IP.To4() != nil {
					fmt.Println(ipnet.IP.String())
				}
			}
		}
	}
}

No comments:

Post a Comment

Caching is a technique used to store frequently accessed data in a temporary storage layer to improve system performance and reduce latency....