server1.c 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  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. int main() {
  8. int sockfd;
  9. char buffer[50];
  10. char sbuf[50];
  11. struct sockaddr_in server_addr, client_addr;
  12. socklen_t client_len;
  13. if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
  14. perror("Socket creation failed");
  15. exit(EXIT_FAILURE);
  16. }
  17. memset(&server_addr, 0, sizeof(server_addr));
  18. server_addr.sin_family = AF_INET;
  19. server_addr.sin_addr.s_addr = INADDR_ANY; // Bind to any address
  20. server_addr.sin_port = htons(PORT);
  21. if (bind(sockfd, (const struct sockaddr *)&server_addr, sizeof(server_addr)) < 0) {
  22. perror("Bind failed");
  23. close(sockfd);
  24. exit(EXIT_FAILURE);
  25. }
  26. printf("Server listening on port %d\n", PORT);
  27. while (1) {
  28. client_len = sizeof(client_addr);
  29. int n = recvfrom(sockfd, buffer, sizeof(buffer), 0, (struct sockaddr *)&client_addr, &client_len);
  30. buffer[n] = '\0'; // Null-terminate the received string
  31. printf("Received message: %s\n", buffer);
  32. int length = n;
  33. sprintf(sbuf,"%d",n);
  34. sendto(sockfd, sbuf, sizeof(sbuf), 0, (const struct sockaddr *)&client_addr, client_len);
  35. }
  36. close(sockfd);
  37. return 0;
  38. }