Home >Backend Development >Golang >golang query domain name ip
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.
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"
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.
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.
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!