Advertisement
Guest User

Untitled

a guest
Feb 2nd, 2021
206
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.84 KB | None | 0 0
  1. #include <fcntl.h>
  2. #include <unistd.h>
  3. #include <stdio.h>
  4. #include <sys/socket.h>
  5. #include <arpa/inet.h>
  6. #include <netinet/in.h>
  7.  
  8. #define PORT 8080
  9.  
  10. int main(void)
  11. {
  12. int master_sock;
  13. int sock;
  14. struct sockaddr_in address;
  15. int opt = 1;
  16. int addrlen = sizeof(address);
  17. char str[4096] = {0};
  18.  
  19. // allocating socket
  20. if (!(master_sock = socket(AF_INET, SOCK_STREAM, 0))) {
  21. perror("\nERROR: SOCKET ALLOCATION FAILED\n");
  22. return 1;
  23. }
  24.  
  25. // attaching socket to the port 8080
  26. if (setsockopt(master_sock, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt))) {
  27. perror("\nERROR: ATTACHING SOCKET TO THE PORT 8080 FAILED\n");
  28. return 1;
  29. }
  30.  
  31. address.sin_family = AF_INET;
  32. address.sin_addr.s_addr = INADDR_ANY;
  33. address.sin_port = htons(PORT);
  34.  
  35. // bind
  36. if (bind(master_sock, (struct sockaddr*) &address, sizeof(address)) < 0) {
  37. perror("\nERROR: BIND FAILED\n");
  38. return 1;
  39. }
  40.  
  41. // try to specify maximum of 3 pending connections for the master socket
  42. if (listen(master_sock, 3) < 0) {
  43. perror("\nERROR: LISTEN\n");
  44. return 1;
  45. }
  46.  
  47. printf("listening on port 8080...\n");
  48. fflush(stdin);
  49.  
  50. if ((sock = accept(master_sock, (struct sockaddr*) &address, (socklen_t*) &addrlen)) < 0) {
  51. perror("\nERROR: ACCEPT FAILED\n");
  52. return 1;
  53. }
  54.  
  55. printf("connection accepted!\n");
  56. fflush(stdout);
  57.  
  58. close(0);
  59. dup(sock);
  60. while (1) {
  61. scanf("%s", str);
  62. printf("%s", str);
  63. fflush(stdout);
  64. }
  65.  
  66. return(0);
  67. }
  68.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement