getmxrr

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

查询主机的 MX 邮件交换记录,按引用回填主机与权重数组。

C C23

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

int main(void) {
    // 无 MX API:需手写 DNS 报文或 c-ares/libldns;示例仅展示 getaddrinfo 主机解析
    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;
}
输出
127.0.0.1

C++ C++26

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

int main() {
    // 无 MX API(c-ares/libldns 补齐);示例仅展示 getaddrinfo 主机解析
    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;
}
输出
127.0.0.1

C# v11.0.100

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

// 标准库无 MX 查询 API(惯用 DnsClient 库补齐);演示能力上限:仅主机名解析
var ip = Array.Find(Dns.GetHostAddresses("localhost"),
    // 按 IPv4 地址族过滤
    a => a.AddressFamily == AddressFamily.InterNetwork);
Console.WriteLine(ip);
输出
127.0.0.1

Go v1.27.4

v1.27.4
package main

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

func main() {
	// LookupMX:标准库 MX 查询,返回 []*MX(Pref 权重 + Host 主机)
	mxs, err := net.LookupMX("gmail.com")
	if err != nil {
		fmt.Println("查询失败:", err)
		return
	}
	// 按优先级升序;Host 带尾点需去除
	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, "."))
	}
}
输出
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:取 MX 属性并解析 "权重 主机." 记录串
        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));
    }
}
输出
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:标准库 MX 查询,回填 {exchange, priority} 数组
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(/\.$/, ""));
  }
})();
输出
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:查到返回 true 并按引用回填 hosts/weights 两组数据
var_dump(getmxrr("gmail.com", $hosts, $weights));
// 权重升序联合排序
array_multisort($weights, $hosts);
foreach (array_slice($hosts, 0, 3, true) as $i => $host) {
    echo $weights[$i], " ", $host, "\n";
}
输出
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


# 标准库无 MX 查询(实战惯用 dnspython);手写 UDP 查询并回填主机/权重两组数据
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)
输出
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;

// 标准库无 MX 查询:手写 UDP 客户端回填权重/主机(实战惯用 hickory-resolver)
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();
    // 构造查询报文:递归标志 + 单个 MX 问题
    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];

    // 解析域名(含压缩指针)
    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);
    }
}
输出
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 回填 {exchange, priority} 数组
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(/\.$/, ""));
  }
})();
输出
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

语言差异说明

C:无 MX API——手写 DNS 报文或 c-ares/libldns;示例 getaddrinfo 只展示标准库主机解析。

C++:同 C;Boost.Asio 有 resolver 但仍仅主机解析,记录级靠第三方。

C#:System.Net.Dns 无 MX;惯用 DnsClient NuGet 包(Resolve<MxRecord>)。

Go:net.LookupMX 一步到位,*MX 切片含 Pref/Host;错误即 err != nil,无 PHP 式 bool。

Java:JNDI DNS 按属性名取 MX;记录串形如 "5 gmail-smtp-in.l.google.com.",权重主机一体需自己拆。

JavaScript:dns.resolveMx 回填 {exchange, priority} 数组;MX 查不到会 reject(NXDOMAIN),与 PHP 返回 false 的语义差异。

PHP:getmxrr 是 MX 专用便捷函数——返回 bool,$hosts/$weights 按引用回填且一一对应;记录级通用查询用 dns_get_record(DNS_MX)。

Python:标准库无 MX;dnspython 的 dns.resolver.resolve(domain, "MX") 是事实标准——示例手写 UDP 演示协议。

Rust:手写 UDP 或 hickory-resolver(Resolver::lookup 指定 RecordType::MX);示例演示报文组装与应答解析。

TypeScript:同 JavaScript,dns/promises 的 resolveMx。