UDP Socket Programming Basics
You'll learn how UDP socket programming differs from TCP and how to send and receive datagrams without establishing a connection.
Core Difference: No Connection Setup
Unlike TCP socket programming, where you call listen(), accept(), and connect() to establish a connection before exchanging data, UDP skips all of that. There's no handshake, no connection state—just fire-and-forget datagram delivery.
Think of it like the difference between a phone call (TCP) and dropping postcards in a mailbox (UDP). With postcards, you don't dial, wait for someone to pick up, or confirm they're ready to receive. You just write the address and send it.
Key Operations: sendto and recvfrom
Since UDP is connectionless, you must specify the destination address every time you send data:
-
sendto(): Sends a datagram to a specific IP address and port. You pass the data, the recipient's address, and port in each call. -
recvfrom(): Receives a datagram and tells you who sent it. Unlike TCP'srecv(), this returns both the data and the sender's address.
You don't need separate accept() or connect() calls—the socket can communicate with multiple peers by simply changing the address in sendto().
Programming Flow
UDP Server:
- Create socket
- Bind to a port
- Loop:
recvfrom()to get data and sender address - Optionally
sendto()back to that sender
UDP Client:
- Create socket
sendto()directly to server's address- Optionally
recvfrom()for a response
Key Takeaway: UDP socket programming uses sendto() and recvfrom() instead of connection-oriented operations, allowing you to send datagrams directly to any address without establishing or maintaining a connection.