UDP Socket Programming Basics
What you'll learn: How to create and use UDP sockets in application code to send and receive datagrams between networked programs.
Core Idea
UDP socket programming involves four fundamental operations: creating a socket, binding it to a port, sending data with sendto(), and receiving data with recvfrom(). Unlike TCP's connection-oriented approach, UDP sockets operate statelessly—you simply fire off datagrams to destinations without establishing a connection first.
Creating and Binding UDP Sockets
When you create a UDP socket, you ask the operating system for a communication endpoint. You specify that you want a datagram-style (UDP) socket rather than a stream-style (TCP) socket.
Binding associates your socket with a specific port number on your machine. Think of binding like claiming a mailbox number—other programs now know where to send you UDP datagrams. Servers typically bind to well-known ports so clients can find them.
Sending Data with sendto()
The sendto() function lets you fire off a datagram to any destination. You provide:
- The socket to send from
- The data buffer
- The destination IP address and port
Each call is independent—no connection needed. It's like addressing and mailing a postcard every time you communicate.
Receiving Data with recvfrom()
The recvfrom() function waits for incoming datagrams. When one arrives, it fills your buffer with the data and tells you who sent it (their IP and port). This return information is crucial since UDP doesn't maintain connection state—you need to know where to send replies.
Unlike TCP's recv(), which just reads from an established connection, recvfrom() handles messages from anyone who knows your port.
Key Takeaway: UDP socket programming centers on four operations: creating sockets, binding to ports, using sendto() to fire datagrams at destinations, and using recvfrom() to receive datagrams while learning who sent them—all without connection establishment.