Write 2 C programs (Client and Server) and establish a communication between them using…
- User
Write 2 C programs (Client and Server) and establish a communication between them using UDP sockets.
Assistant
Below are two simple C programs, one for a UDP server and one for a UDP client. These programs will establish a communication channel using UDP sockets, where the client sends a message to the server, and the server responds back to the client.
Important Notes:
- Error Handling: Comprehensive error handling has been added to ensure the programs behave predictably in case of errors.
- Compilation: To compile these programs, use
gccwith the-oflag to specify the output file name. The compilation commands are provided at the end of each code snippet.
UDP Server Program (
udp_server.c)c#include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #define BUFFER_SIZE 1024 #define PORT 8080 int main() { int sockfd, len; struct sockaddr_in server_addr, client_addr; socklen_t client_len = sizeof(client_addr); char buffer[BUFFER_SIZE]; // Create socket sockfd = socket(AF_INET, SOCK_DGRAM, 0); if (sockfd < 0) { perror("socket creation failed"); exit(1); } // Set address and port number for the server server_addr.sin_family = AF_INET; server_addr.sin_port = htons(PORT); server_addr.sin_addr.s_addr = INADDR_ANY; // Listen on all available network interfaces // Bind the socket to the port if (bind(sockfd, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0) { perror("bind failed"); exit(1); } printf("Server listening on port %d...\n", PORT); while (1) { // Receive message from client len = recvfrom(sockfd, buffer, BUFFER_SIZE, 0, (struct sockaddr *)&client_addr, &client_len); if (len < 0) { perror("recvfrom failed"); continue; } buffer[len] = '\0'; // Null terminate the received message printf("Received from client: %s\n", buffer); // Send response back to client char* message = "Hello, Client!"; printf("Sending to client: %s\n", message); if (sendto(sockfd, message, strlen(message), 0, (struct sockaddr *)&client_addr, client_len) < 0) { perror("sendto failed"); } } // Close the socket (added for completeness) close(sockfd); return 0; }
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.