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
Certainly! Below are two simple C programs: one for a UDP server and one for a UDP client. The server will listen on a specific port and echo back any message it receives. The client will send a message to the server and print the response.
UDP Server
Save this as
udp_server.c.c#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <arpa/inet.h> #include <sys/socket.h> #include <netinet/in.h> #define PORT 8080 int main() { int sockfd, n; struct sockaddr_in servaddr, cliaddr; // Create socket sockfd = socket(AF_INET, SOCK_DGRAM, 0); if (sockfd < 0) { perror("socket creation failed"); exit(EXIT_FAILURE); } // Set up the server address structure memset(&servaddr, 0, sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_addr.s_addr = INADDR_ANY; servaddr.sin_port = htons(PORT); // Bind the socket to the address if (bind(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr)) < 0) { perror("bind failed"); exit(EXIT_FAILURE); } printf("Server listening on port %d\n", PORT); while (1) { char buffer[1024]; int len; // Receive message from client len = recvfrom(sockfd, buffer, sizeof(buffer), 0, (struct sockaddr *)&cliaddr, (socklen_t*)&len); if (len < 0) { perror("recvfrom failed"); exit(EXIT_FAILURE); } printf("Received message: %s\n", buffer); // Echo the message back to client sendto(sockfd, buffer, len, 0, (struct sockaddr *)&cliaddr, sizeof(cliaddr)); } close(sockfd); return 0; } - User
how do i know this is udp?
- Assistant
You can identify that these programs use UDP (User Datagram Protocol) by looking at the following aspects of the code:
-
Socket creation: In both the server and client programs, the socket is created using the
socket()function with theSOCK_DGRAMparameter, which indicates a datagram socket (UDP). For TCP, you would useSOCK_STREAM.csockfd = socket(AF_INET, SOCK_DGRAM, 0); -
Communication functions: The programs use
sendto()andrecvfrom()functions for sending and receiving data, which are typically used for connectionless communication in UDP. In contrast, TCP usesconnect(),send(), andrecv()functions for connection-oriented communication.csendto(sockfd, buffer, strlen(buffer), 0, (struct sockaddr *)&servaddr, sizeof(servaddr)); recvfrom(sockfd, buffer, sizeof(buffer), 0, (struct sockaddr *)&servaddr, (socklen_t*)&len);
-
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.