UDP
User Datagram Protocol
A connectionless transport protocol. Fast but unreliable. Streaming, gaming.
User Datagram Protocol
A connectionless transport protocol. Fast but unreliable. Streaming, gaming.
UDP (User Datagram Protocol) is a connectionless protocol that operates at the transport layer of the TCP/IP model. Unlike TCP, it sends data immediately without connection setup (3-way handshake), and it has no packet ordering guarantee or retransmission mechanism. Thanks to these characteristics, its overhead is very low and it is optimized for real-time data transmission.
The UDP header consists of only 8 bytes (source port, destination port, length, checksum). Compared to the TCP header, which is at least 20 bytes, it is very lightweight. Because the overhead per packet is small, it is efficient in situations where a large number of small packets must be sent quickly. This is also why DNS queries use UDP.
UDP is preferred in real-time streaming, online games, VoIP (Voice over IP), video conferencing, and similar applications. In these applications, receiving the next data quickly is more important than waiting for retransmission, even if a single packet is lost. For example, in a video call, it is more natural to hear the current voice than to have a voice packet from 0.5 seconds ago retransmitted.
In the modern web, the QUIC protocol runs on top of UDP. HTTP/3 is based on QUIC and combines the speed of UDP with the reliability of TCP. Large services such as Google, Cloudflare, and Facebook have already adopted HTTP/3, and connections are maintained more reliably when the network switches, especially in mobile environments.
import socket
# ============ UDP 서버 ============
def udp_server():
server = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
server.bind(('0.0.0.0', 9999))
print("UDP 서버 시작: 포트 9999")
while True:
data, client_addr = server.recvfrom(1024)
print(f"수신: {data.decode()} from {client_addr}")
server.sendto(b"ACK: " + data, client_addr)
# ============ UDP 클라이언트 ============
def udp_client():
client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# UDP는 connect() 없이 바로 전송 가능
message = "Hello, UDP!"
client.sendto(message.encode(), ('127.0.0.1', 9999))
# 타임아웃 설정 (UDP는 응답 보장 없음)
client.settimeout(2.0)
try:
response, _ = client.recvfrom(1024)
print(f"응답: {response.decode()}")
except socket.timeout:
print("응답 없음 - UDP는 신뢰성 보장 안됨!")
client.close()
# ============ 브로드캐스트 전송 ============
def broadcast_message():
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
# 로컬 네트워크 전체에 메시지 전송
sock.sendto(b"DISCOVER", ('255.255.255.255', 9999))
print("브로드캐스트 전송 완료")
# 실행: python server.py (서버) | python client.py (클라이언트)
# netcat으로 UDP 테스트
# UDP 서버 시작 (-u: UDP 모드)
nc -u -l 9999
# UDP 클라이언트로 메시지 전송 (다른 터미널)
echo "Hello UDP" | nc -u 127.0.0.1 9999
# UDP 포트 스캔 (열린 UDP 포트 확인)
nmap -sU -p 53,123,161 192.168.1.1
# UDP 패킷 캡처 (tcpdump)
sudo tcpdump -i eth0 udp port 53
# DNS 쿼리 (UDP 53 포트 사용)
dig @8.8.8.8 google.com +short
# UDP 연결 상태 확인
netstat -anu | grep 9999
ss -anu | grep 9999
# iperf3로 UDP 대역폭 테스트
# 서버
iperf3 -s -u -p 5201
# 클라이언트 (100Mbps로 테스트)
iperf3 -c 192.168.1.100 -u -b 100M -p 5201
# socat으로 UDP 릴레이
socat UDP-LISTEN:9999,fork UDP:192.168.1.100:9999
# 특정 UDP 포트로 데이터 전송 (bash)
exec 3<>/dev/udp/127.0.0.1/9999
echo "Test message" >&3
const dgram = require('dgram');
// ============ UDP 서버 ============
const server = dgram.createSocket('udp4');
server.on('message', (msg, rinfo) => {
console.log(`수신: ${msg} from ${rinfo.address}:${rinfo.port}`);
// 응답 전송
const response = Buffer.from(`ACK: ${msg}`);
server.send(response, rinfo.port, rinfo.address);
});
server.on('listening', () => {
const addr = server.address();
console.log(`UDP 서버 시작: ${addr.address}:${addr.port}`);
});
server.bind(9999);
// ============ UDP 클라이언트 ============
const client = dgram.createSocket('udp4');
const message = Buffer.from('Hello, UDP!');
client.send(message, 9999, '127.0.0.1', (err) => {
if (err) console.error('전송 실패:', err);
else console.log('메시지 전송 완료');
});
// 응답 대기 (타임아웃 처리)
const timeout = setTimeout(() => {
console.log('응답 없음 - 타임아웃');
client.close();
}, 2000);
client.on('message', (msg) => {
clearTimeout(timeout);
console.log(`응답: ${msg}`);
client.close();
});
// ============ 멀티캐스트 예제 ============
const multicast = dgram.createSocket({ type: 'udp4', reuseAddr: true });
multicast.bind(5000, () => {
multicast.addMembership('239.255.255.250'); // 멀티캐스트 그룹 참가
console.log('멀티캐스트 그룹 참가 완료');
});
multicast.on('message', (msg, rinfo) => {
console.log(`멀티캐스트 수신: ${msg}`);
});
"Real-time position synchronization should be handled over UDP, while important data such as chat or payments should be separated onto TCP. Even if packet loss occurs with UDP, it's fine because the next frame's position information arrives right away. TCP, on the other hand, can suffer head-of-line blocking because of retransmission, so let's keep it on a separate connection."
"The biggest differences between TCP and UDP are connection orientation and reliability. TCP establishes a connection with a 3-way handshake and guarantees packet ordering and retransmission, whereas UDP sends right away without these processes. DNS uses UDP because queries are usually small, at 512 bytes or less, and if there is no response, the client can simply retry."
"In voice calls, users notice interruptions when the delay exceeds 200ms. I think going with a UDP + RTP combination and setting a jitter buffer of around 50ms would be appropriate. If the packet loss rate is 1% or less, users barely notice it, so please set up alerts in quality monitoring based on that threshold."
Take a mock interview on this topic → WIA SOOM AI Interview · Start for free
You must not send data that must not be lost, such as payment information, login tokens, and stored data, over UDP. UDP does not detect packet loss, so it won't know if data disappears. Always use TCP for important data.
The maximum UDP datagram size is 65,507 bytes, but if it exceeds the MTU (usually 1500 bytes), IP fragmentation occurs. If even one of the fragmented packets is lost, the whole datagram is discarded, so in practice keep packets at 1472 bytes (1500-28) or less.
Many corporate firewalls allow TCP but block UDP. When developing WebRTC or game servers, you should prepare a TCP fallback or a TURN server in case UDP is blocked. Check whether a UDP connection is possible with a STUN test first.
Separate data where real-time performance matters (game positions, voice, video) onto UDP, and data where reliability matters (login, payments, chat) onto TCP. Add sequence numbers and timestamps at the application level to manage ordering and delay.