Networking in C · advanced · ~10 min

UDP client

Send a single datagram to a peer.

Lesson

UDP is connectionless. Create a SOCK_DGRAM socket and call sendto(...) with the destination address each time. Receive with recvfrom, which fills in the sender's address.

Packets may be lost, reordered, or duplicated. Applications add their own retry/sequence logic when needed.

Code examples

int s = socket(AF_INET, SOCK_DGRAM, 0);
struct sockaddr_in a = {0};
a.sin_family = AF_INET; a.sin_port = htons(53);
inet_pton(AF_INET, "127.0.0.1", &a.sin_addr);
sendto(s, "hi", 2, 0, (struct sockaddr*)&a, sizeof a);