Menu Close

Go – How to get host addresses of host in Go

Here, we will help you to understand how to get host addresses of host in Go. We will learn about LookupHost() method to get host addresses of host in go.

Function prototype:

func LookupHost(host string) (addrs []string, err error)

Input parameters:

host: Host name like techieindoor.com

Return value:

LookupHost() of net package is used to return a slice of that host’s addresses.

Example with code:

package main

import (
  "fmt"
  "net"
)


func main() {

    host_addresses, err := net.LookupHost("techieindoor.com")

    if err == nil {

        for _, addr := range(host_addresses) {

            fmt.Println("Host address: ", addr)

        }

    } else {

        fmt.Print("Invalid host name. Error is: ", err)

    }
}

Output:

$ go run sample.go

Host address:  172.67.133.84
Host address:  104.21.5.106
Host address:  2606:4700:3032::6815:56a
Host address:  2606:4700:3036::ac43:8554

Example with invalid host name:

package main

import (
  "fmt"
  "net"
)


func main() {

    host_addresses, err := net.LookupHost("helloInvalid.com")

    if err == nil {

        for _, addr := range(host_addresses) {

            fmt.Println("Host address: ", addr)

        }

    } else {

        fmt.Print("Invalid host name. Error is: ", err)

    }
}

Output:

$: go run sample.go

Invalid host name. Error is: lookup helloInvalid.com: no such host

To learn more about golang, Please refer given below link:

https://techieindoor.com/go-lang-tutorial/

References:

https://golang.org/doc/
https://golang.org

Posted in golang, net

Leave a Reply

Your email address will not be published. Required fields are marked *