Advertisement
4doorsmorehories

Server Go Back N

Apr 18th, 2023
41
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.88 KB | None | 0 0
  1. #include <netinet/in.h>
  2. #include <stdio.h>
  3. #include <time.h>
  4. #include <stdlib.h>
  5. #include <string.h>
  6. #include <sys/socket.h>
  7. #include <unistd.h>
  8. #define PORT 8080
  9. #define window_size 5
  10. void transfer(int sock){
  11.     struct timeval tv;
  12.     tv.tv_sec = 1;
  13.     tv.tv_usec = 0;
  14.     setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, (const char*)&tv, sizeof tv);
  15.     srand(time(NULL));
  16.     int head=0,tail=0,count,red;
  17.       printf("Enter number of frames:");
  18.       scanf("%d",&count);
  19.       for(tail=0;tail<count;tail++){
  20.       red=-1;
  21.       if((tail-head)>window_size||tail==count-1)
  22.       { printf("Timeout resend from %d\n",head);
  23.       tail=head;
  24.       }
  25.       int flag = rand()%2;
  26.       printf("frame %d send\n",tail);
  27.       if(!flag)
  28.       {write(sock,&tail,sizeof(tail));
  29.         }
  30.         read(sock,&red,sizeof(red));
  31.         if(red!=-1){head++;
  32.         printf("\nACK %d\n",red);}
  33.        
  34.       }
  35.      
  36.        
  37. }
  38.  
  39. int main(int argc, char const* argv[])
  40. {
  41.     int server_fd, new_socket;
  42.     struct sockaddr_in address;
  43.     int opt = 1,n;
  44.     int addrlen = sizeof(address);
  45.     if ((server_fd = socket(AF_INET, SOCK_STREAM, 0))
  46.         == 0) {
  47.         perror("socket failed");
  48.         exit(EXIT_FAILURE);
  49.     }
  50.     if (setsockopt(server_fd, SOL_SOCKET,
  51.                 SO_REUSEADDR | SO_REUSEPORT, &opt,
  52.                 sizeof(opt))) {
  53.         perror("setsockopt");
  54.         exit(EXIT_FAILURE);
  55.     }
  56.     address.sin_family = AF_INET;
  57.     address.sin_addr.s_addr = INADDR_ANY;
  58.     address.sin_port = htons(PORT);
  59.     if (bind(server_fd, (struct sockaddr*)&address,
  60.             sizeof(address))
  61.         < 0) {
  62.         perror("bind failed");
  63.         exit(EXIT_FAILURE);
  64.     }
  65.     if (listen(server_fd, 3) < 0) {
  66.         perror("listen");
  67.         exit(EXIT_FAILURE);
  68.     }
  69.     if ((new_socket
  70.         = accept(server_fd, (struct sockaddr*)&address,
  71.                 (socklen_t*)&addrlen))
  72.         < 0) {
  73.         perror("accept");
  74.         exit(EXIT_FAILURE);
  75.     }
  76.    
  77.     transfer(new_socket);
  78.     close(new_socket);
  79.     shutdown(server_fd, SHUT_RDWR);
  80.     return 0;
  81. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement