dns_get_record

dns_get_record(string $hostname, int $type = DNS_ANY, array &$authoritative_name_servers = null, array &$additionals = null, bool $raw = false): array|false

Fetches DNS records (A/MX/NS/SOA, ...) for a hostname and returns the record array.

C C23

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

int main(void) {
    // The C standard library only has getaddrinfo hostname resolution: no standard API for record-level queries like MX/NS/SOA
    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() {
    // C++ same as C: the standard library only has getaddrinfo; record-level queries need third-party libraries like c-ares/libldns
    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;

// C#'s standard library has no record-level queries (MX/NS/SOA): the Dns class does hostname resolution only; the DnsClient library fills the gap idiomatically
foreach (var ip in Dns.GetHostAddresses("localhost")) {
    if (ip.AddressFamily == AddressFamily.InterNetwork) {
        Console.WriteLine(ip); // Demonstrating the standard library's ceiling: A/AAAA only
        break;
    }
}
Output
127.0.0.1

Go v1.27.4

v1.27.4
package main

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

func main() {
	// net.LookupMX: standard-library record-level MX query (via the system resolver)
	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("type: MX")
	for _, m := range mxs[:3] {
		fmt.Println(m.Pref, strings.TrimSuffix(m.Host, "."))
	}
}
Output
type: MX
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 {
        // The JNDI DNS provider (built into the JDK): query records by attribute name
        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[]> pris = new ArrayList<>();
        List<String> hosts = new ArrayList<>();
        for (Enumeration<?> e = attrs.get("MX").getAll(); e.hasMoreElements(); ) {
            String v = (String) e.nextElement(); // Shaped like "5 gmail-smtp-in.l.google.com."
            Matcher m = Pattern.compile("(\\d+) (.+)").matcher(v);
            if (m.matches()) {
                pris.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 -> pris.get(i)[0]));
        System.out.println("type: MX");
        for (int i : idx.subList(0, 3)) System.out.println(pris.get(i)[0] + " " + hosts.get(i));
    }
}
Output
type: MX
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
// Node's built-in resolver: resolveMx is the MX record query (resolveAny is the closest to dns_get_record)
const dns = require("node:dns").promises;

(async () => {
  const records = await dns.resolveMx("gmail.com");
  records.sort((a, b) => a.priority - b.priority);
  console.log("type: MX");
  for (const r of records.slice(0, 3)) {
    console.log(r.priority, r.exchange.replace(/\.$/, ""));
  }
})();
Output
type: MX
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
// dns_get_record: record type selected by a DNS_* constant, returns the record array
$records = dns_get_record("gmail.com", DNS_MX);
echo "fields: ", implode(", ", array_keys($records[0])), "\n";
echo "type: ", $records[0]["type"], "\n";
// MX sorted by pri ascending
usort($records, fn($a, $b) => $a["pri"] <=> $b["pri"]);
foreach (array_slice($records, 0, 3) as $r) {
    echo $r["pri"], " ", $r["target"], "\n";
}
Output
fields: host, class, ttl, type, pri, target
type: MX
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 record-level DNS queries in the standard library (idiomatically dnspython in real projects); a minimal hand-written UDP client demos the MX query
def query_mx(domain):
    header = struct.pack(">HHHHHH", 0x1234, 0x0100, 1, 0, 0, 0)
    q = b"".join(bytes([len(p)]) + p.encode() for p in domain.split(".")) + b"\x00"
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    sock.settimeout(5)
    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
    out = []
    for _ in range(an):
        _, off = read_name(data, off)
        rtype, _, _, rdlen = struct.unpack(">HHIH", data[off:off + 10])
        off += 10
        if rtype == 15:
            pri = struct.unpack(">H", data[off:off + 2])[0]
            host, _ = read_name(data, off + 2)
            out.append((pri, host))
        off += rdlen
    return sorted(out)


print("type: MX")
for pri, host in query_mx("gmail.com")[:3]:
    print(pri, host)
Output
type: MX
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 DNS library in Rust's standard library: the hickory-resolver crate is idiomatic; a minimal hand-written UDP client demos the MX query
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![0x12, 0x34, 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() {
    println!("type: MX");
    for (pri, host) in query_mx("gmail.com").into_iter().take(3) {
        println!("{} {}", pri, host);
    }
}
Output
type: MX
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
// Node built-in resolver: resolveMx queries MX records
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("type: MX");
  for (const r of records.slice(0, 3)) {
    console.log(r.priority, r.exchange.replace(/\.$/, ""));
  }
})();
Output
type: MX
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: the standard library only has getaddrinfo/gethostbyname name resolution; record-level queries need hand-written DNS packets (UDP 53) or c-ares/libldns.

C++: same as C — no standard DNS library; the getaddrinfo("localhost") example just shows the name-resolution ceiling; real work uses c-ares wrappers.

C#: System.Net.Dns does name resolution only (A/AAAA); no MX/NS/SOA API — the DnsClient NuGet package is the usual fix.

Go: net.LookupMX/LookupNS/LookupTXT query records in the standard library; net.Resolver can target a custom DNS server.

Java: no dedicated DNS API in the standard library — the built-in JNDI DNS provider (com.sun.jndi.dns.DnsContextFactory) is the idiom, reading records by attribute name.

JavaScript: Node ships a resolver — dns.promises.resolveMx/resolveTxt/resolveAny; resolveAny is closest to dns_get_record (all types at once).

PHP: dns_get_record selects the type via DNS_* constants (DNS_MX/DNS_A/DNS_ANY, ...); records carry host/class/ttl/type fields; the two by-ref parameters also return authoritative NS and additional records.

Python: the standard library only has socket.getaddrinfo (name resolution); record-level queries usually use the third-party dnspython — the example hand-writes UDP packets to show the protocol layer.

Rust: no standard DNS library; hickory-resolver (formerly trust-dns) is the idiom; the example hand-writes a minimal UDP client to parse an MX answer.

TypeScript: same as JavaScript — Node's dns/promises is a standard-library-grade DNS client.