getmxrr

getmxrr(string $hostname, array &$hosts, array &$weights = null): bool

Queries a host's MX mail-exchange records, filling the hosts and weights arrays by reference.

C C23

C23
#include <arpa/inet.h>
#include <netdb.h>
#include <stdio.h>
#include <sys/socket.h>

int main(void) {
    // No MX API: hand-written DNS packets or c-ares/libldns; the demo shows only getaddrinfo hostname resolution
    struct addrinfo hints = {0}, *res;
    hints.ai_family = AF_INET;
    if (getaddrinfo("localhost", NULL, &hints, &res) != 0) return 1;
    char ip[INET_ADDRSTRLEN];
    struct sockaddr_in *addr = (struct sockaddr_in *)res->ai_addr;
    inet_ntop(AF_INET, &addr->sin_addr, ip, sizeof ip);
    printf("%s\n", ip);
    freeaddrinfo(res);
    return 0;
}
Output
127.0.0.1

C++ C++26

C++26
#include <arpa/inet.h>
#include <iostream>
#include <netdb.h>
#include <sys/socket.h>

int main() {
    // No MX API (fill the gap with c-ares/libldns); the demo shows only getaddrinfo hostname resolution
    addrinfo hints{};
    hints.ai_family = AF_INET;
    addrinfo *res = nullptr;
    if (getaddrinfo("localhost", nullptr, &hints, &res) != 0) return 1;
    char ip[INET_ADDRSTRLEN];
    inet_ntop(AF_INET, &((sockaddr_in *)res->ai_addr)->sin_addr, ip, sizeof ip);
    std::cout << ip << "\n";
    freeaddrinfo(res);
    return 0;
}
Output
127.0.0.1

C# v11.0.100

v11.0.100
using System.Net;
using System.Net.Sockets;

// No MX query API in the standard library (the DnsClient library fills the gap idiomatically); demo ceiling: hostname resolution only
var ip = Array.Find(Dns.GetHostAddresses("localhost"),
    a => a.AddressFamily == AddressFamily.InterNetwork);
Console.WriteLine(ip);
Output
127.0.0.1

Go v1.27.4

v1.27.4
package main

import (
	"fmt"
	"net"
	"sort"
	"strings"
)

func main() {
	// LookupMX: standard-library MX query returning []*MX (Pref weight + Host name)
	mxs, err := net.LookupMX("gmail.com")
	if err != nil {
		fmt.Println("查询失败:", err)
		return
	}
	sort.Slice(mxs, func(i, j int) bool { return mxs[i].Pref < mxs[j].Pref })
	fmt.Println("found:", len(mxs) > 0)
	for _, m := range mxs[:3] {
		fmt.Println(m.Pref, strings.TrimSuffix(m.Host, "."))
	}
}
Output
found: true
5 gmail-smtp-in.l.google.com
10 alt1.gmail-smtp-in.l.google.com
20 alt2.gmail-smtp-in.l.google.com

Java v27.0.1

v27.0.1
import java.util.*;
import java.util.regex.*;
import javax.naming.Context;
import javax.naming.directory.*;

public class Main {
    public static void main(String[] args) throws Exception {
        // JNDI DNS: fetch the MX attribute and parse "weight host." record strings
        Hashtable<String, Object> env = new Hashtable<>();
        env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.dns.DnsContextFactory");
        DirContext ctx = new InitialDirContext(env);
        Attributes attrs = ctx.getAttributes("gmail.com", new String[]{"MX"});
        List<int[]> weights = new ArrayList<>();
        List<String> hosts = new ArrayList<>();
        for (Enumeration<?> e = attrs.get("MX").getAll(); e.hasMoreElements(); ) {
            Matcher m = Pattern.compile("(\\d+) (.+)").matcher((String) e.nextElement());
            if (m.matches()) {
                weights.add(new int[]{Integer.parseInt(m.group(1))});
                hosts.add(m.group(2).replaceAll("\\.$", ""));
            }
        }
        List<Integer> idx = new ArrayList<>();
        for (int i = 0; i < hosts.size(); i++) idx.add(i);
        idx.sort(Comparator.comparingInt(i -> weights.get(i)[0]));
        System.out.println("found: " + (!hosts.isEmpty()));
        for (int i : idx.subList(0, 3)) System.out.println(weights.get(i)[0] + " " + hosts.get(i));
    }
}
Output
found: true
5 gmail-smtp-in.l.google.com
10 alt1.gmail-smtp-in.l.google.com
20 alt2.gmail-smtp-in.l.google.com

JavaScript v26.13.1

v26.13.1
// dns.resolveMx: standard-library MX query, filling the {exchange, priority} array
const dns = require("node:dns").promises;

(async () => {
  const records = await dns.resolveMx("gmail.com");
  records.sort((a, b) => a.priority - b.priority);
  console.log("found:", records.length > 0);
  for (const r of records.slice(0, 3)) {
    console.log(r.priority, r.exchange.replace(/\.$/, ""));
  }
})();
Output
found: true
5 gmail-smtp-in.l.google.com
10 alt1.gmail-smtp-in.l.google.com
20 alt2.gmail-smtp-in.l.google.com

PHP v8.6.0

v8.6.0
$hosts = [];
$weights = [];
// getmxrr: returns true on a hit, filling hosts/weights by reference
var_dump(getmxrr("gmail.com", $hosts, $weights));
array_multisort($weights, $hosts); // Joint sort by weight ascending
foreach (array_slice($hosts, 0, 3, true) as $i => $host) {
    echo $weights[$i], " ", $host, "\n";
}
Output
bool(true)
5 gmail-smtp-in.l.google.com
10 alt1.gmail-smtp-in.l.google.com
20 alt2.gmail-smtp-in.l.google.com

Python v3.15.2

v3.15.2
import socket
import struct


# No MX query in the standard library (idiomatically dnspython in real projects); hand-written UDP query filling the host/weight arrays
def get_mx(domain):
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    sock.settimeout(5)
    header = struct.pack(">HHHHHH", 0x4321, 0x0100, 1, 0, 0, 0)
    q = b"".join(bytes([len(p)]) + p.encode() for p in domain.split(".")) + b"\x00"
    sock.sendto(header + q + struct.pack(">HH", 15, 1), ("8.8.8.8", 53))
    data, _ = sock.recvfrom(2048)
    sock.close()

    def read_name(buf, off):
        labels, jumped, end = [], False, 0
        while True:
            n = buf[off]
            if n & 0xC0 == 0xC0:
                if not jumped:
                    end = off + 2
                off = ((n & 0x3F) << 8) | buf[off + 1]
                jumped = True
                continue
            off += 1
            if n == 0:
                if not jumped:
                    end = off
                return ".".join(labels), end
            labels.append(buf[off:off + n].decode())
            off += n

    qd, an = struct.unpack(">HH", data[4:8])
    off = 12
    for _ in range(qd):
        _, off = read_name(data, off)
        off += 4
    hosts, weights = [], []
    for _ in range(an):
        _, off = read_name(data, off)
        rtype, _, _, rdlen = struct.unpack(">HHIH", data[off:off + 10])
        off += 10
        if rtype == 15:
            weights.append(struct.unpack(">H", data[off:off + 2])[0])
            host, _ = read_name(data, off + 2)
            hosts.append(host)
        off += rdlen
    return hosts, weights


hosts, weights = get_mx("gmail.com")
pairs = sorted(zip(weights, hosts))
print("found:", bool(pairs))
for weight, host in pairs[:3]:
    print(weight, host)
Output
found: True
5 gmail-smtp-in.l.google.com
10 alt1.gmail-smtp-in.l.google.com
20 alt2.gmail-smtp-in.l.google.com

Rust v1.99.1

v1.99.1
use std::net::UdpSocket;
use std::time::Duration;

// No MX query in the standard library: hand-written UDP client filling weights/hosts (hickory-resolver is idiomatic in real projects)
fn query_mx(domain: &str) -> Vec<(u16, String)> {
    let socket = UdpSocket::bind("0.0.0.0:0").expect("bind failed");
    socket
        .set_read_timeout(Some(Duration::from_secs(5)))
        .unwrap();
    let mut pkt = vec![0x43, 0x21, 0x01, 0x00, 0, 1, 0, 0, 0, 0, 0, 0];
    for label in domain.split('.') {
        pkt.push(label.len() as u8);
        pkt.extend_from_slice(label.as_bytes());
    }
    pkt.push(0);
    pkt.extend_from_slice(&15u16.to_be_bytes()); // QTYPE=MX
    pkt.extend_from_slice(&1u16.to_be_bytes()); // QCLASS=IN
    socket.send_to(&pkt, "8.8.8.8:53").unwrap();

    let mut buf = vec![0u8; 2048];
    let n = socket.recv(&mut buf).unwrap();
    let data = &buf[..n];

    // Parse the domain name (compression pointers included)
    fn read_name(data: &[u8], mut off: usize) -> (String, usize) {
        let mut labels = Vec::new();
        let mut jumped = false;
        let mut end = 0usize;
        loop {
            let len = data[off];
            if len & 0xC0 == 0xC0 {
                if !jumped {
                    end = off + 2;
                }
                off = (((len & 0x3F) as usize) << 8) | data[off + 1] as usize;
                jumped = true;
                continue;
            }
            off += 1;
            if len == 0 {
                if !jumped {
                    end = off;
                }
                return (labels.join("."), end);
            }
            labels.push(String::from_utf8_lossy(&data[off..off + len as usize]).into_owned());
            off += len as usize;
        }
    }

    let answers = u16::from_be_bytes([data[6], data[7]]) as usize;
    let mut off = 12usize;
    for _ in 0..u16::from_be_bytes([data[4], data[5]]) as usize {
        let (_, next) = read_name(data, off);
        off = next + 4;
    }
    let mut out = Vec::new();
    for _ in 0..answers {
        let (_, next) = read_name(data, off);
        off = next;
        let rtype = u16::from_be_bytes([data[off], data[off + 1]]);
        let rdlen = u16::from_be_bytes([data[off + 8], data[off + 9]]) as usize;
        off += 10;
        if rtype == 15 {
            let pri = u16::from_be_bytes([data[off], data[off + 1]]);
            let (host, _) = read_name(data, off + 2);
            out.push((pri, host));
        }
        off += rdlen;
    }
    out.sort();
    out
}

fn main() {
    let mxs = query_mx("gmail.com");
    println!("found: {}", !mxs.is_empty());
    for (pri, host) in mxs.into_iter().take(3) {
        println!("{} {}", pri, host);
    }
}
Output
found: true
5 gmail-smtp-in.l.google.com
10 alt1.gmail-smtp-in.l.google.com
20 alt2.gmail-smtp-in.l.google.com

TypeScript v26.13.1

v26.13.1
// dns.resolveMx fills {exchange, priority} arrays
import { promises as dns } from "node:dns";

(async () => {
  const records = await dns.resolveMx("gmail.com");
  records.sort((a, b) => a.priority - b.priority);
  console.log("found:", records.length > 0);
  for (const r of records.slice(0, 3)) {
    console.log(r.priority, r.exchange.replace(/\.$/, ""));
  }
})();
Output
found: true
5 gmail-smtp-in.l.google.com
10 alt1.gmail-smtp-in.l.google.com
20 alt2.gmail-smtp-in.l.google.com

Language differences

C: no MX API — hand-written DNS packets or c-ares/libldns; the getaddrinfo example only shows standard-library name resolution.

C++: same as C; Boost.Asio has a resolver but still name-level only — record-level needs a third-party library.

C#: System.Net.Dns has no MX; the usual fix is the DnsClient NuGet package (Resolve<MxRecord>).

Go: net.LookupMX does it in one call; a []*MX slice with Pref/Host; errors come back as err != nil, no PHP-style bool.

Java: JNDI DNS reads MX by attribute name; record strings look like "5 gmail-smtp-in.l.google.com." — weight and host in one string you split yourself.

JavaScript: dns.resolveMx fills {exchange, priority} arrays; a missing MX rejects the promise, unlike PHP's false return.

PHP: getmxrr is the dedicated MX helper — returns bool and fills $hosts/$weights by reference in matching order; for general record queries use dns_get_record(DNS_MX).

Python: no MX in the standard library; dnspython's dns.resolver.resolve(domain, "MX") is the de facto standard — the example hand-writes UDP to show the protocol.

Rust: hand-written UDP or hickory-resolver (Resolver::lookup with RecordType::MX); the demo shows packet assembly and answer parsing.

TypeScript: same as JavaScript — resolveMx from dns/promises.