client_udp.c 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  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 sock_value;
  11. char buffer[BUFFER_SIZE];
  12. struct sockaddr_in server_addr={0};
  13. socklen_t server_len = sizeof(server_addr);
  14. //Create UDP socket
  15. if ((sock_value = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
  16. {
  17. perror("Socket creation failed");
  18. exit(EXIT_FAILURE);
  19. }
  20. server_addr.sin_family = AF_INET;
  21. server_addr.sin_port = htons(PORT);
  22. // Convert IP address from text to binary form
  23. if (inet_pton(AF_INET, "127.0.0.1", &server_addr.sin_addr) <= 0)
  24. {
  25. perror("Invalid address / Address not supported");
  26. close(sock_value);
  27. exit(EXIT_FAILURE);
  28. }
  29. printf("Enter a message to send to the server: ");
  30. fgets(buffer, sizeof(buffer), stdin);
  31. // Remove trailing newline character from fgets
  32. buffer[strcspn(buffer, "\n")] = '\0';
  33. //
  34. // Send message to the server
  35. sendto(sock_value, (const char *)buffer, strlen(buffer), MSG_CONFIRM, (const struct sockaddr *)&server_addr, server_len);
  36. printf("Message sent to server: %s\n", buffer);
  37. //receive
  38. int n = recvfrom(sock_value, (char *)buffer, BUFFER_SIZE, MSG_WAITALL, (struct sockaddr *)&server_addr, &server_len);
  39. buffer[n] = '\0'; // Null-terminate the received data
  40. printf("Server responded with message length: %s\n", buffer);
  41. //
  42. //Close the socket
  43. close(sock_value);
  44. }