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

Golang: Http POST Request with JSON Body example

Go standard library comes with "net/http" package which has excellent support for HTTP Client and Server.   In order to post JSON ...