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

9 Comments

  1. Mickie

    Good day I am so delighted I found your site, I really found you by mistake, while I was searching on Digg for something else, Anyhow I
    am here now and would just like to say many thanks for a marvelous post and a all round interesting blog (I also love
    the theme/design), I don’t have time to read it all at the minute but I have book-marked it and
    also included your RSS feeds, so when I have time I will be back to read a great deal more,
    Please do keep up the excellent work.

  2. Raleigh NC

    Simply want to say your article is as amazing. The
    clarity for your put up is just great and i could
    assume you are a professional in this subject. Fine with your
    permission allow me to grab your feed to keep up to date with forthcoming post.
    Thanks a million and please keep up the gratifying work.

Leave a Reply

Your email address will not be published.

Contact Us