checkdnsrr

checkdnsrr(string $hostname, string $type = "MX"): bool

Checks whether a host has DNS records of a given type (A/MX/NS/TXT, ...), returning true when found — the existence check of the DNS trio.

C C23

C23
#include <netdb.h>
#include <stdio.h>

/* The standard library only does hostname resolution: getaddrinfo success/failure is exactly A/AAAA existence semantics;
   record-level queries like MX/NS need hand-written DNS packets or c-ares */
static int host_exists(const char *host) {
    struct addrinfo hints = {0}, *res;
    hints.ai_family = AF_UNSPEC;
    if (getaddrinfo(host, NULL, &hints, &res) != 0) return 0;
    freeaddrinfo(res);
    return 1;
}

int main(void) {
    printf("A: %d\n", host_exists("gmail.com"));
    printf("MX: unsupported\n"); /* No record-level API */
    printf("missing: %d\n", host_exists("no-such-host-a1b2c3.example.com"));
    return 0;
}
Output
A: 1
MX: unsupported
missing: 0

C++ C++26

C++26
#include <iostream>
#include <netdb.h>

// Same as C: getaddrinfo success/failure is exactly A/AAAA existence semantics; record-level queries need a third-party library
static bool host_exists(const char *host) {
    addrinfo hints{};
    hints.ai_family = AF_UNSPEC;
    addrinfo *res = nullptr;
    if (getaddrinfo(host, nullptr, &hints, &res) != 0) return false;
    freeaddrinfo(res);
    return true;
}

int main() {
    std::cout << "A: " << host_exists("gmail.com") << "\n";
    std::cout << "MX: unsupported\n"; // No record-level API
    std::cout << "missing: " << host_exists("no-such-host-a1b2c3.example.com") << "\n";
    return 0;
}
Output
A: 1
MX: unsupported
missing: 0

C# v11.0.100

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

// A record existence: GetHostAddresses throws SocketException on failure; MX has no stdlib API (idiomatically filled by DnsClient)
bool aExists(string host)
{
    try { Dns.GetHostAddresses(host); return true; }
    catch (SocketException) { return false; }
}
Console.WriteLine($"A: {aExists("gmail.com")}");
Console.WriteLine("MX: N/A (标准库无 MX 查询)");
Console.WriteLine($"missing: {aExists("no-such-host-a1b2c3.example.com")}");
Output
A: True
MX: N/A (标准库无 MX 查询)
missing: False

Go v1.27.4

v1.27.4
package main

import (
	"fmt"
	"net"
)

func main() {
	// LookupHost/LookupMX: err != nil means absence — the error IS the semantics, no PHP-style bool
	aOK := false
	if _, err := net.LookupHost("gmail.com"); err == nil {
		aOK = true
	}
	fmt.Println("A:", aOK)
	mxOK := false
	if mxs, err := net.LookupMX("gmail.com"); err == nil && len(mxs) > 0 {
		mxOK = true
	}
	fmt.Println("MX:", mxOK)
	missingOK := true
	if _, err := net.LookupHost("no-such-host-a1b2c3.example.com"); err != nil {
		missingOK = false
	}
	fmt.Println("missing:", missingOK)
}
Output
A: true
MX: true
missing: false

Java v27.0.1

v27.0.1
import java.net.InetAddress;
import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.directory.Attributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;

public class Main {
    // A record existence: getByName throws UnknownHostException on failure
    static boolean canResolve(String host) {
        try {
            InetAddress.getByName(host);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    // MX record existence: the built-in JNDI DNS provider fetches MX by attribute name
    static boolean mxExists(String host) {
        try {
            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(host, new String[]{"MX"});
            return attrs.get("MX") != null && attrs.get("MX").size() > 0;
        } catch (Exception e) {
            return false;
        }
    }

    public static void main(String[] args) {
        System.out.println("A: " + canResolve("gmail.com"));
        System.out.println("MX: " + mxExists("gmail.com"));
        System.out.println("missing: " + canResolve("no-such-host-a1b2c3.example.com"));
    }
}
Output
A: true
MX: true
missing: false

JavaScript v26.13.1

v26.13.1
// dns.resolve/resolveMx: a failed query (NXDOMAIN/no records) rejects — turn it into a bool with then(ok, miss)
const dns = require("node:dns").promises;

(async () => {
  console.log("A:", await dns.resolve("gmail.com").then(() => true, () => false));
  console.log("MX:", await dns.resolveMx("gmail.com").then((r) => r.length > 0, () => false));
  console.log("missing:", await dns.resolve("no-such-host-a1b2c3.example.com").then(() => true, () => false));
})();
Output
A: true
MX: true
missing: false

PHP v8.6.0

v8.6.0
// checkdnsrr: the existence check of the DNS trio (paired with getmxrr/dns_get_record) — returns bool
var_dump(checkdnsrr("gmail.com", "A"));
var_dump(checkdnsrr("gmail.com", "MX"));
// NXDOMAIN → false (absence and query failure both return false)
var_dump(checkdnsrr("no-such-host-a1b2c3.example.com", "A"));
Output
bool(true)
bool(true)
bool(false)

Python v3.15.2

v3.15.2
import socket
import struct


def mx_exists(domain):
    # No MX query in the standard library: a minimal hand-written UDP query judged by RCODE/answer count (idiomatically dnspython in real projects)
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    sock.settimeout(5)
    header = struct.pack(">HHHHHH", 0x2222, 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()
    rcode = struct.unpack(">H", data[2:4])[0] & 0x0F
    answers = struct.unpack(">H", data[6:8])[0]
    return rcode == 0 and answers > 0


def a_exists(host):
    # A/AAAA existence: getaddrinfo failure (gaierror) means absence
    try:
        socket.getaddrinfo(host, None)
        return True
    except socket.gaierror:
        return False


print("A:", a_exists("gmail.com"))
print("MX:", mx_exists("gmail.com"))
print("missing:", a_exists("no-such-host-a1b2c3.example.com"))
Output
A: True
MX: True
missing: False

Rust v1.99.1

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

// No DNS in the standard library: a minimal hand-written UDP query judged by RCODE/answer count for existence (idiomatically hickory-resolver in real projects)
fn record_exists(domain: &str, qtype: u16) -> bool {
    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![0x55, 0xaa, 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(&qtype.to_be_bytes());
    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 rcode = buf[3] & 0x0F;
    let answers = u16::from_be_bytes([buf[6], buf[7]]);
    rcode == 0 && answers > 0
}

fn main() {
    println!("A: {}", record_exists("gmail.com", 1));
    println!("MX: {}", record_exists("gmail.com", 15));
    println!("missing: {}", record_exists("no-such-host-a1b2c3.example.com", 1));
}
Output
A: true
MX: true
missing: false

TypeScript v26.13.1

v26.13.1
// dns.resolve/resolveMx reject on failure (NXDOMAIN/no records) — turn it into a boolean
import { promises as dns } from "node:dns";

(async () => {
  console.log("A:", await dns.resolve("gmail.com").then(() => true, () => false));
  console.log("MX:", await dns.resolveMx("gmail.com").then((r) => r.length > 0, () => false));
  console.log("missing:", await dns.resolve("no-such-host-a1b2c3.example.com").then(() => true, () => false));
})();
Output
A: true
MX: true
missing: false

Language differences

C: the standard library only has getaddrinfo name resolution — its success/failure is exactly the A/AAAA existence semantics; MX/NS-level queries need hand-written DNS packets or c-ares.

C++: same as C; Boost.Asio is also name-level only.

C#: Dns.GetHostAddresses does the existence check (a SocketException on failure); no standard MX API — the DnsClient NuGet package fills the gap.

Go: net.LookupHost/LookupMX — err != nil means nonexistent; the error is the semantics, no PHP-style bool.

Java: A via InetAddress.getByName (UnknownHostException on failure); MX via the built-in JNDI DNS provider by attribute name.

JavaScript: dns.resolve/resolveMx — a failed query (NXDOMAIN/no records) rejects the promise; turn it into a boolean with then(ok, miss).

PHP: checkdnsrr is the existence check of the DNS trio (paired with getmxrr/dns_get_record) — returns a bool, with $type as a string ("A"/"MX"/"NS"...); nonexistent and failed queries both yield false.

Python: A via socket.getaddrinfo (gaierror on failure); no MX in the standard library — the example hand-writes UDP and checks RCODE/answer count; dnspython is the norm in real work.

Rust: no DNS in std — the example hand-writes a minimal UDP query and checks RCODE/ANCOUNT; hickory-resolver is the norm.

TypeScript: same as JavaScript (dns/promises).