server.c 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. #include<stdio.h>
  2. #include<stdlib.h>
  3. #include<string.h>
  4. #include <unistd.h>
  5. #include <arpa/inet.h>
  6. #define PORT 12345
  7. #define BUFFER_SIZE 1024
  8. int main()
  9. {
  10. int server_socket, client_socket;
  11. struct sockaddr_in server_addr, client_addr;
  12. socklen_t client_addr_len;
  13. char buffer[BUFFER_SIZE];
  14. if ((server_socket = socket(AF_INET, SOCK_STREAM, 0)) < 0)
  15. {
  16. perror("Socket creation failed");
  17. exit(EXIT_FAILURE);
  18. }
  19. // Define server address
  20. server_addr.sin_family = AF_INET;
  21. server_addr.sin_addr.s_addr = INADDR_ANY;
  22. server_addr.sin_port = htons(PORT);
  23. // Bind the socket to the address and port
  24. if (bind(server_socket, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0)
  25. {
  26. perror("Bind failed");
  27. close(server_socket);
  28. exit(EXIT_FAILURE);
  29. }
  30. // Listen for incoming connections
  31. if (listen(server_socket, 5) < 0)
  32. {
  33. perror("Listen failed");
  34. close(server_socket);
  35. exit(EXIT_FAILURE);
  36. }
  37. printf("Server listening on port %d...\n", PORT);
  38. // Accept incoming client connection
  39. client_addr_len = sizeof(client_addr);
  40. if ((client_socket = accept(server_socket, (struct sockaddr *)&client_addr, &client_addr_len)) < 0)
  41. {
  42. perror("Client connection failed");
  43. close(server_socket);
  44. exit(EXIT_FAILURE);
  45. }
  46. printf("Client connected. Waiting for message...\n");
  47. // Receive message from the client
  48. //int n = recv(client_socket, buffer, BUFFER_SIZE, 0);
  49. //if (n < 0)
  50. // {
  51. // perror("Receive failed");
  52. // close(client_socket);
  53. // close(server_socket);
  54. // exit(EXIT_FAILURE);
  55. //}
  56. //buffer[n] = '\0'; // Null-terminate the received string
  57. //printf("Received from client: %s\n", buffer);
  58. // Send response to the client
  59. //const char *response = "Hello, Client! Your message was received.";
  60. //send(client_socket, response, strlen(response), 0);
  61. // printf("Response sent to client.\n");
  62. // Close the sockets
  63. close(client_socket);
  64. close(server_socket);
  65. return 0;
  66. }