client.c 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <unistd.h>
  5. #include <arpa/inet.h>
  6. #define PORT 8081
  7. #define BUFFER_SIZE 1024
  8. int main() {
  9. int sock = 0;
  10. struct sockaddr_in serv_addr;
  11. char *message = "Hello Server\n";
  12. char buffer[BUFFER_SIZE] = {0};
  13. if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
  14. printf("\n Socket creation error \n");
  15. return -1;
  16. }
  17. serv_addr.sin_family = AF_INET;
  18. serv_addr.sin_port = htons(PORT);
  19. if (inet_pton(AF_INET, "127.0.0.1", &serv_addr.sin_addr) <= 0) {
  20. printf("\nInvalid address\n");
  21. return -1;
  22. }
  23. if (connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) {
  24. printf("\nConnection Failed \n");
  25. return -1;
  26. }
  27. send(sock, message, strlen(message), 0);
  28. printf("Message sent to server: %s", message);
  29. int read_size = read(sock, buffer, BUFFER_SIZE);
  30. if (read_size > 0) {
  31. printf("Received from server: %s", buffer);
  32. }
  33. close(sock);
  34. return 0;
  35. }