Standard library / net

net.Resolver.LookupMX()

Retrieve mail exchanger records, ordered by preference with equal preferences randomized. Lower preference values are preferred. The context bounds the lookup; a custom Dial hook directs this example to a local synthetic responder. Expected stdout: 'mail.invalid. 10\n'.

Formal Syntax & Structure

go syntaxgo
func (r *Resolver) LookupMX(ctx context.Context, name string) ([]*MX, error)

Parameters & Attributes

NameTypeDescription
ctxcontext.ContextContext controlling cancellation.
namestringDNS name to query, including a trailing dot for an absolute name.

Return Value

([]*MX, error)

Operation result; check errors and validity indicators when returned.

Working Example

Example Snippetgo
package main
import (  "context"  "encoding/binary"  "fmt"  "net"  "strings"  "time")
func main() {  r, stop := dnsFixture()  defer stop()  ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)  defer cancel()  v := must(r.LookupMX(ctx, "demo.invalid."))  fmt.Println(v[0].Host, v[0].Pref)}
// dnsFixture is a deliberately small, UDP-only synthetic DNS responder.// It accepts only the uncompressed single-question format emitted by the Go resolver.// No host resolver configuration is changed and no external queries are made.func dnsFixture() (*net.Resolver, func()) {  pc := must(net.ListenPacket("udp4", "127.0.0.1:0"))  done := make(chan struct{})  go func() {    defer close(done)    b := make([]byte, 4096)    for {      n, peer, err := pc.ReadFrom(b)      if err != nil {        return      }      if response := dnsResponse(b[:n]); response != nil {        _, _ = pc.WriteTo(response, peer)      }    }  }()  r := &net.Resolver{PreferGo: true, Dial: func(ctx context.Context, network, address string) (net.Conn, error) {    return (&net.Dialer{}).DialContext(ctx, network, pc.LocalAddr().String())  }}  return r, func() { _ = pc.Close(); <-done }}func wireName(s string) []byte {  var b []byte  for _, label := range strings.Split(strings.TrimSuffix(s, "."), ".") {    b = append(b, byte(len(label)))    b = append(b, label...)  }  return append(b, 0)}func dnsResponse(q []byte) []byte {  if len(q) < 17 || binary.BigEndian.Uint16(q[4:6]) != 1 {    return nil  }  i := 12  var labels []string  for {    if i >= len(q) {      return nil    }    n := int(q[i])    i++    if n == 0 {      break    }    if n > 63 || i+n > len(q) {      return nil    }    labels = append(labels, string(q[i:i+n]))    i += n  }  if i+4 > len(q) {    return nil  }  name := strings.ToLower(strings.Join(labels, ".")) + "."  typ := binary.BigEndian.Uint16(q[i : i+2])  end := i + 4  out := append([]byte(nil), q[:end]...)  binary.BigEndian.PutUint16(out[2:4], 0x8180)  for j := 6; j < 12; j++ {    out[j] = 0  }  count := uint16(0)  record := func(owner string, t uint16, data []byte) {    out = append(out, wireName(owner)...)    out = binary.BigEndian.AppendUint16(out, t)    out = binary.BigEndian.AppendUint16(out, 1)    out = binary.BigEndian.AppendUint32(out, 60)    out = binary.BigEndian.AppendUint16(out, uint16(len(data)))    out = append(out, data...)    count++  }  a := []byte{192, 0, 2, 7}  aaaa := net.ParseIP("2001:db8::7").To16()  switch name {  case "demo.invalid.", "alias.invalid.", "partial.invalid.":    owner := name    if name == "alias.invalid." {      record(name, 5, wireName("demo.invalid."))      owner = "demo.invalid."    }    if name == "partial.invalid." && typ == 28 {      out[3] = 0x82      break    }    switch typ {    case 1:      record(owner, 1, a)    case 28:      record(owner, 28, aaaa)    case 15:      record(owner, 15, append([]byte{0, 10}, wireName("mail.invalid.")...))    case 2:      record(owner, 2, wireName("ns.invalid."))    case 16:      record(owner, 16, []byte{5, 'h', 'e', 'l', 'l', 'o'})    }  case "_demo._tcp.demo.invalid.":    if typ == 33 {      record(name, 33, append([]byte{0, 10, 0, 5, 0x1f, 0x90}, wireName("service.invalid.")...))    }  case "7.2.0.192.in-addr.arpa.":    if typ == 12 {      record(name, 12, wireName("demo.invalid."))    }  default:    out[3] = 0x83  }  binary.BigEndian.PutUint16(out[6:8], count)  return out}
func must[T any](v T, e error) T {  if e != nil {    panic(e)  }  return v}func check(e error) {  if e != nil {    panic(e)  }}
Go Reference