client.c 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <unistd.h>
  5. #include <arpa/inet.h>
  6. #define SERVER_ADDR "127.0.0.1"
  7. #define PORT 8083
  8. #define BUFFER_SIZE 1024
  9. int main()
  10. {
  11. int client_socket;
  12. struct sockaddr_in server_addr={0};
  13. char buffer[BUFFER_SIZE];
  14. // Create socket
  15. if ((client_socket = socket(AF_INET, SOCK_STREAM, 0)) < 0)
  16. {
  17. perror("Socket creation failed");
  18. exit(EXIT_FAILURE);
  19. }
  20. // Define server address
  21. server_addr.sin_family = AF_INET;
  22. server_addr.sin_port = htons(PORT);
  23. server_addr.sin_addr.s_addr = inet_addr(SERVER_ADDR);
  24. // Convert IP address to binary form
  25. //if (inet_pton(AF_INET, "127.0.0.1", &server_addr.sin_addr) <= 0)
  26. //{
  27. // perror("Invalid address");
  28. //exit(EXIT_FAILURE);
  29. //}
  30. // Connect to the server
  31. if (connect(client_socket, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0)
  32. {
  33. perror("Connection failed");
  34. close(client_socket);
  35. exit(EXIT_FAILURE);
  36. }
  37. printf("Connected to server\n");
  38. //for(int i=0;i<6;i++)
  39. // {
  40. // Send a message to the server
  41. const char *message = "testing!";
  42. send(client_socket, message, strlen(message), 0);
  43. printf("Message sent to server: %s\n",message );
  44. //}
  45. //Receive server's response
  46. int n = recv(client_socket, buffer, BUFFER_SIZE, 0);
  47. if (n < 0)
  48. {
  49. perror("Receive failed");
  50. close(client_socket);
  51. exit(EXIT_FAILURE);
  52. }
  53. buffer[n] = '\0'; // Null-terminate the received string
  54. printf("Received from server: %s\n", buffer);
  55. // Close the socket
  56. close(client_socket);
  57. return 0;
  58. }