Junior — Middle
What is the main role and purpose of the UDP protocol in network communications?
sobes.tech AI
Answer from AI
The UDP (User Datagram Protocol) is used for transmitting data in networks without establishing a connection. Its main role is to provide fast and simple delivery of packets with minimal delay, without guarantees of delivery, order, or integrity.
UDP is suitable for applications where speed is crucial and some packet loss is acceptable, such as:
- Video conferencing and VoIP — delays are critical, and packet loss is not always noticeable.
- Online gaming — real-time updates are important.
- DNS queries — short requests and responses.
Unlike TCP, UDP does not establish a connection, confirm receipt, or perform retransmission, which reduces overhead and delays.
Example of creating a UDP socket in C++:
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
int sock = socket(AF_INET, SOCK_DGRAM, 0);
sockaddr_in addr{};
addr.sin_family = AF_INET;
addr.sin_port = htons(12345);
addr.sin_addr.s_addr = inet_addr("127.0.0.1");
const char* msg = "Hello UDP";
sendto(sock, msg, strlen(msg), 0, (sockaddr*)&addr, sizeof(addr));