UDP & DNS
UDP AND DNS
1. UDP (User Datagram Protocol)
UDP is a "connectionless" protocol. Unlike TCP, it doesn't check if the receiver is ready or if the data actually arrived. It simply sends "datagrams" into the network.
Why use UDP?
Low Latency: No handshake, no acknowledgement packets, and no re-transmission delays.
Best For: Real-time applications where losing a tiny bit of data is better than waiting (e.g., Video calls, Online Gaming, or VoIP).
UDP in Node.js: The dgram Module
Node.js uses the dgram module to handle UDP.
const dgram = require('dgram');
const server = dgram.createSocket('udp4');
server.on('message', (msg, rinfo) => {
console.log(`Received: ${msg} from ${rinfo.address}:${rinfo.port}`);
});
server.bind(41234);2. DNS (Domain Name System)
DNS is the "address book" of the internet. It translates human-readable domain names (like careeroza.com) into machine-readable IP addresses (like 192.0.2.1).
In Node.js, the dns module provides two ways to resolve names:
System-level resolution: Uses the underlying operating system facilities (synchronous-like behavior).
Network-level resolution: Performs actual DNS queries over the network.
const dns = require('dns');
// Finding the IP address of a domain
dns.lookup('google.com', (err, address, family) => {
console.log('IP Address:', address); // e.g., 142.250.190.46
});
// Finding Mail Server (MX) records
dns.resolveMx('careeroza.com', (err, addresses) => {
console.log('Mail Servers:', addresses);
});
| Method | Discription |
|---|---|
| dns.lookup() | uses the OS's getaddrinfo.it's what most apps use to find an IP |
| dns.resolve() | Performs a network query for specific records (A, MX, TXT, etc ). |
| dns.reverse() | Takes an IP address and looks up the domain name |
3. How UDP and DNS Work Together
DNS almost always uses UDP on Port 53.
The Workflow: When you type a URL, your computer sends a small UDP packet containing a DNS query. Because the query is tiny, the overhead of a TCP handshake would be a waste of time.
The Exception: If a DNS response is too large for a single UDP packet (over 512 bytes), it automatically switches to TCP to ensure the data isn't truncated.
4. Summary: Choosing the Right Tool
Use
net(TCP) when you need a 100% reliable connection (File transfers, Chat, APIs).Use
dgram(UDP) when speed is more important than perfect data (Live streaming, Discovery services).Use
dnswhen you need to find where a server is located or verify domain ownership (via TXT records).