server.c 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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 server_fd, new_socket;
  10. struct sockaddr_in address;
  11. int opt = 1;
  12. int addrlen = sizeof(address);
  13. char buffer[BUFFER_SIZE] = {0};
  14. if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) {
  15. perror("Socket failed");
  16. exit(EXIT_FAILURE);
  17. }
  18. address.sin_family = AF_INET;
  19. address.sin_addr.s_addr = INADDR_ANY;
  20. address.sin_port = htons(PORT);
  21. if (bind(server_fd, (struct sockaddr *)&address, sizeof(address)) < 0) {
  22. perror("Bind failed");
  23. exit(EXIT_FAILURE);
  24. }
  25. if (listen(server_fd, 3) < 0) {
  26. perror("Listen");
  27. exit(EXIT_FAILURE);
  28. }
  29. printf("Server listening on port %d\n", PORT);
  30. if ((new_socket = accept(server_fd, (struct sockaddr *)&address, (socklen_t*)&addrlen)) < 0) {
  31. perror("Accept");
  32. exit(EXIT_FAILURE);
  33. }
  34. while (1) {
  35. memset(buffer, 0, BUFFER_SIZE);
  36. int read_size = read(new_socket, buffer, BUFFER_SIZE);
  37. if (read_size == 0) {
  38. printf("Client disconnected\n");
  39. break;
  40. }
  41. printf("Received: %s", buffer);
  42. send(new_socket, buffer, read_size, 0);
  43. printf("Echoed back: %s", buffer);
  44. }
  45. close(new_socket);
  46. close(server_fd);
  47. return 0;
  48. }