Result Arrays
The simplest way to get DNS results is to use the Golang standard library. It works well if you are looking for simple answers.
There are several Lookup
functions:
net.LookupAddr
net.LookupCNAME
net.LookupHost
net.LookupIP
net.LookupMX
net.LookupNS
net.LookupPort
net.LookupSRV
net.LookupTXT
Many of the above use a type struct for the result. These include:
net.IP
net.MX
net.NS
net.SRV
All of the above requires the right import:
import "net"
Name -> IP
The most common usage is find an IP based on a name.
ip, err := net.LookupIP("example.com")
if err != nil {
panic(err)
}
fmt.Println(ip)
fmt.Println(ip[0])
The result is an array so has to be dereferenced.
[127.0.0.1]
127.0.0.1
The other option is to get the results as strings, so replace the first line:
ipString, err := net.LookupHost("example.com")
The result of this sample would look the same as the first sample due to string conversation.
One item to note is that these calls return both IPv4 and IPv6 addresses.
IP -> Name
You can reverse the name from a given IP:
n, err := net.LookupAddr("127.0.0.1")
if err != nil {
panic(err)
}
fmt.Println(n)
results in:
[localhost]
Alias
DNS allows for some names to point to other names. The net.LookupHost
and net.LookupIP
calls dereference the alias before returning the result, but sometimes you want to know the alias instead.
n, err := net.LookupCNAME("mail.google.com")
if err != nil {
panic(err)
}
fmt.Println(n)
results in:
googlemail.l.google.com.
At this point, you’re free to resolve the IP as shown in the first examples.
Mail eXchanger
The MX record designates multiple endpoints to connect to just for sending mail to. Typically, a domain will have MX records so that users can have @domain addresses without all of those having to connect to a server where the domain points.
An MX record consists of a name and a priority. The name is a DNS name which can be resolved to an IP to be connected to. The priority is the order (lower first) which servers are supposed to be tried.
mxes, err := net.LookupMX("google.com")
if err != nil {
panic(err)
}
for _, mx := range mxes {
fmt.Println(mx)
}
results in:
&{aspmx.l.google.com. 10}
&{alt1.aspmx.l.google.com. 20}
&{alt2.aspmx.l.google.com. 30}
&{alt3.aspmx.l.google.com. 40}
&{alt4.aspmx.l.google.com. 50}
The first item is the name, and the second is the priority.
Name Server
The Name Server is the unit of delegation in DNS. To find a name server:
nses, err := net.LookupNS("google.com")
if err != nil {
panic(err)
}
for _, ns := range nses {
fmt.Println(ns)
}
results in:
&{ns4.google.com.}
&{ns2.google.com.}
&{ns1.google.com.}
&{ns3.google.com.}
Like with CNAMEs and MXes, these names can then be looked up to get the final info.