server_udp.c 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <unistd.h>
  5. #include <arpa/inet.h>
  6. #define PORT 8080
  7. #define BUFFER_SIZE 1024
  8. void main()
  9. {
  10. int socket_value;
  11. char message[BUFFER_SIZE];
  12. struct sockaddr_in server_addr={0};
  13. struct sockaddr_in client_addr;
  14. socklen_t client_len = sizeof(client_addr);
  15. // socket creation
  16. if((socket_value=socket(AF_INET,SOCK_DGRAM,0)) <0)
  17. {
  18. perror("server socket creation error");
  19. exit(EXIT_FAILURE);
  20. }
  21. //server addr speciifications
  22. server_addr.sin_family = AF_INET;
  23. server_addr.sin_addr.s_addr = INADDR_ANY;
  24. server_addr.sin_port = htons(PORT);
  25. // bind the socket to the port in server
  26. if(bind(socket_value,(struct sockaddr*)&server_addr,sizeof(server_addr))<0)
  27. {
  28. perror("bind fail");
  29. close(socket_value);
  30. exit(EXIT_FAILURE);
  31. }
  32. printf("server is listening on port\n");
  33. // receive message from client..
  34. while(1)
  35. {
  36. int len=recvfrom(socket_value, (char *)message, BUFFER_SIZE, MSG_WAITALL, (struct sockaddr *)&client_addr, &client_len);
  37. message[len]='\0';
  38. printf("%s/n",message);
  39. // Send the length of the received message back to the client
  40. int message_length = strlen(message);
  41. snprintf(message, sizeof(message), "%d", message_length); // Convert length to string
  42. sendto(socket_value, (const char *)message, strlen(message), MSG_CONFIRM, (const struct sockaddr *)&client_addr, client_len);
  43. printf("Sent message length to client: %d\n", message_length);
  44. }
  45. close(socket_value);
  46. }