#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define PORT 8080
#define MAX_BUFFER_SIZE 1024
int main() {
int sockfd;
struct sockaddr_in server_address, client_address;
socklen_t address_length = sizeof(client_address);
char buffer[MAX_BUFFER_SIZE];
// Creating socket file descriptor
if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
perror("Socket creation failed");
exit(EXIT_FAILURE);
}
memset(&server_address, 0, sizeof(server_address));
memset(&client_address, 0, sizeof(client_address));
// Server information
server_address.sin_family = AF_INET;
server_address.sin_addr.s_addr = INADDR_ANY;
server_address.sin_port = htons(PORT);
// Binding the socket with the server address
if (bind(sockfd, (const struct sockaddr *)&server_address, sizeof(server_address)) < 0) {
perror("Bind failed");
exit(EXIT_FAILURE);
}
printf("Server started. Listening on port %d...\n", PORT);
while (1) {
// Receiving data from client
int data_length = recvfrom(sockfd, (char *)buffer, MAX_BUFFER_SIZE, MSG_WAITALL, (struct sockaddr *)&client_address, &address_length);
buffer[data_length] = '\0';
// Printing the received message
printf("Received message from %s:%d: %s\n", inet_ntoa(client_address.sin_addr), ntohs(client_address.sin_port), buffer);
// Sending acknowledgment to the client
char ack_message[] = "Message received by the server";
sendto(sockfd, (const char *)ack_message, strlen(ack_message), 0, (const struct sockaddr *)&client_address, address_length);
}
close(sockfd);
return 0;
}
This is a simple UDP server that binds to a specific port (8080 in this example) and listens for incoming messages from clients. When it receives a message, it prints the message along with the client's IP address and port number. Then, it sends an acknowledgment message back to the client.