Menu Close

Go – How to find IP Address by domain name in Go

Here, we will help you to understand how to find IP address by domain name in Go. We will learn it by example and program.

LookupIP() method of net package is used to find IP address by domain name in go.

Function prototype:

func LookupIP(host string) ([]IP, error)

Input parameters:
host: Domain name (Eg. techieindoor.com)

Return value:

LookupIP() function in net package returns slice of host’s IPv4 and IPv6 addresses

Example with code:

package main

import (
  "fmt"
  "net"
  "log"
)


func main() {

  ip_list, err := net.LookupIP("techieindoor.com")

  if err == nil {

      fmt.Println("IPs are: ")

      for _, ip := range ip_list {


          fmt.Println(ip)

      }

  } else {

      log.Fatal("IP lookup failed. Error is: ", err)

  }
}

Output:

$ go run sample.go

IPs are:
104.21.5.106
172.67.133.84
2606:4700:3032::6815:56a
2606:4700:3036::ac43:8554

Program to find only IPv4 address by domain name in go

package main

import (
  "fmt"
  "net"
  "log"
)


func main() {

  ip_list, err := net.LookupIP("techieindoor.com")

  if err == nil {

      for _, ip := range ip_list {

          if ipv4 := ip.To4(); ipv4 != nil {

              fmt.Println("IPv4: ", ip)

          }

      }

  } else {

      log.Fatal("IP lookup failed. Error is: ", err)

  }
}

Output:

$ go run sample.go

IPv4: 104.21.5.106
IPv4: 172.67.133.84

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

https://www.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.

Contact Us