UDP (User Datagram Protocol) is a connectionless transport layer protocol, suitable for application scenarios with high requirements for real-time performance, such as video streaming, voice communication, online games, etc. Unlike TCP, UDP does not guarantee the reliability and sequence of data, but its transmission speed is faster.
This article will introduce how to write a simple UDP server program in C language and how to receive and process data sent by the client.
1. Introduction to UDP protocol
UDP is a connectionless transport layer protocol with the following characteristics:
No connection: No connection is required, data can be sent directly to the target host.
Unreliability: UDP does not guarantee the order and arrival of packets, and may lose packets.
Message-oriented: Send data in an independent message form, unlike TCP, which requires maintenance of the state of the flow.
High efficiency: UDP transmission efficiency is high since connection establishment and maintenance is not required.
2. Implementing UDP server based on C language
The following will demonstrate how to implement a simple UDP server in C language, including creating sockets, binding addresses, receiving data, and sending responses.
1. Required header files
To implement network programming in C language, the following header files are usually required:
#include <> #include <> #include <> #include <arpa/> #include <sys/> #include <>
2. Create the core code of UDP server
The following is a simple UDP server implementation that listens to the specified port and receives messages sent by the client.
#define PORT 12345 // The port number of the server monitor#define BUFFER_SIZE 1024 // Buffer size int main() { int sockfd; char buffer[BUFFER_SIZE]; struct sockaddr_in server_addr, client_addr; socklen_t addr_len; ssize_t n; // Create UDP socket sockfd = socket(AF_INET, SOCK_DGRAM, 0); if (sockfd < 0) { perror("Socket creation failed"); exit(EXIT_FAILURE); } // Configure the server address memset(&server_addr, 0, sizeof(server_addr)); server_addr.sin_family = AF_INET; // IPv4 server_addr.sin_addr.s_addr = INADDR_ANY; // Accept any IP address server_addr.sin_port = htons(PORT); // Convert the port number to network byte order // Bind the socket to the specified IP address and port if (bind(sockfd, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0) { perror("Binding failed"); close(sockfd); exit(EXIT_FAILURE); } printf("UDP server is started, listening to port %d...\n", PORT); // Receive data cyclically while (1) { addr_len = sizeof(client_addr); // Receive datagrams n = recvfrom(sockfd, buffer, BUFFER_SIZE, 0, (struct sockaddr *)&client_addr, &addr_len); if (n < 0) { perror("Receive data failed"); continue; } buffer[n] = '\0'; // Make sure the string ends with '\0' printf("Received message from %s:%d: %s\n", inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port), buffer); // Send a response const char *response = "The server has received your message"; sendto(sockfd, response, strlen(response), 0, (struct sockaddr *)&client_addr, addr_len); } // Close the socket close(sockfd); return 0; }
3. Code parsing
Create UDP socket: socket(AF_INET, SOCK_DGRAM, 0) function creates a UDP socket, where AF_INET means using IPv4 protocol, and SOCK_DGRAM means using UDP protocol.
Bind server address and port: The bind() function is used to bind a socket to a local address and port, so that the server can listen to requests for the specified port.
Receive datagram: The recvfrom() function is used to receive data from the client and obtain the address information of the sender.
Send response: The sendto() function is used to send data back to the client, and a simple response message is sent here.
Close socket: The server closes the socket before the program exits to free up resources.
4. Compile and run
The above code can be compiled and run using the following command:
gcc -o udp_server udp_server.c ./udp_server
After running, the server will start listening to port 12345 and wait for receiving messages from the client.
5. Test the UDP server
To test the functionality of the server, we can use the following simple UDP client code to send messages:
#include <> #include <> #include <> #include <arpa/> #include <sys/> #include <> #define SERVER_PORT 12345 #define SERVER_IP "127.0.0.1" #define BUFFER_SIZE 1024 int main() { int sockfd; struct sockaddr_in server_addr; char buffer[BUFFER_SIZE]; socklen_t addr_len; // Create UDP socket sockfd = socket(AF_INET, SOCK_DGRAM, 0); if (sockfd < 0) { perror("Socket creation failed"); exit(EXIT_FAILURE); } // Configure the server address memset(&server_addr, 0, sizeof(server_addr)); server_addr.sin_family = AF_INET; server_addr.sin_port = htons(SERVER_PORT); inet_pton(AF_INET, SERVER_IP, &server_addr.sin_addr); // Send a message to the server const char *message = "Hello, UDP Server!"; sendto(sockfd, message, strlen(message), 0, (struct sockaddr *)&server_addr, sizeof(server_addr)); // Receive the server's response addr_len = sizeof(server_addr); ssize_t n = recvfrom(sockfd, buffer, BUFFER_SIZE, 0, (struct sockaddr *)&server_addr, &addr_len); if (n > 0) { buffer[n] = '\0'; printf("Server Response: %s\n", buffer); } // Close the socket close(sockfd); return 0; }
6. Run the client
Compile and run the client program, and send messages to the server and receive responses from the server.
gcc -o udp_client udp_client.c ./udp_client
3. Summary
This article describes how to implement a simple UDP server in C language and how clients communicate with it. Through this sample code, the basic operation steps and usage scenarios of the UDP protocol can be understood. UDP is suitable for scenarios with high requirements for transmission speed and real-time performance, but in practical applications, its unreliability needs to be considered, and additional mechanisms may be needed to ensure the reliability of data transmission.
The above is the detailed content of implementing UDP server based on C language. For more information about C language UDP server, please pay attention to my other related articles!