Home  >  Article  >  Backend Development  >  golang query domain name ip

golang query domain name ip

PHPz
PHPzOriginal
2023-05-13 10:44:37917browse

In network programming, sometimes you need to query the IP address of a domain name. The Golang standard library provides the net package, in which the ResolveIPAddr function can be used to query the IP address of a specified domain name. The following will introduce in detail how to use Golang to query the IP of a domain name.

  1. Import the net package

First, you need to import the net package. This package provides a series of network operation functions and types. With this package, we can use the ResolveIPAddr function to query the IP address of the domain name.

import "net"
  1. Query domain name IP

The function to query domain name IP address is ResolveIPAddr, its prototype is:

func ResolveIPAddr(network, address string) (*IPAddr, error)

The network parameter cannot be empty , which specifies the network type to be queried, which can be "ip4" or "ip6", corresponding to IPv4 addresses and IPv6 addresses. The address parameter is the domain name to be queried.

The code is as follows:

ip, err := net.ResolveIPAddr("ip4", "www.google.com")
if err != nil {
    fmt.Println("Resolve error:", err)
    return
}
fmt.Println(ip.String())

What is queried here is the IPv4 address of the www.google.com domain name. The above code first calls the ResolveIPAddr function to query the IP address of the domain name, and saves the result in the ip variable. If an error occurs, error handling is required. Finally, use the ip.String() function to print the query results in string form.

  1. Query domain name IPv6

If you need to query the IPv6 address, you can modify the first parameter of the query function to "ip6" and modify the domain name to the form of IPv6 address. .

For example, query the IPv6 address code of ipv6.google.com as follows:

ip, err := net.ResolveIPAddr("ip6", "::ffff:172.217.26.238")
if err != nil {
    fmt.Println("Resolve error:", err)
    return
}
fmt.Println(ip.String())

When querying here, convert the IPv4 address 172.217.26.238 into the IPv6 address "::ffff:172.217.26.238" and Passed in as the second parameter.

  1. Summary

net package provides many functions and types required for network programming, and the ResolveIPAddr function can be used to query the IP address of a domain name. When using it, you need to pay attention to the network type and the correct format of the query domain name.

The above is the detailed content of golang query domain name ip. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn