Advertisement
Bewin

ftp_server

Apr 9th, 2025
254
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.30 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <string.h>
  3. #include <sys/socket.h>
  4. #include <arpa/inet.h>
  5. #include <stdlib.h>
  6. #include <unistd.h>
  7.  
  8. int main(void)
  9. {
  10.     FILE *fp;
  11.     char name[100],fileread[100],fname[100],ch,file[100],rcv[100];
  12.     int n;
  13.     int socket_desc, client_sock, client_size;
  14.     struct sockaddr_in server_addr, client_addr;
  15.      
  16.        
  17.     // Create socket:
  18.     socket_desc = socket(AF_INET, SOCK_STREAM, 0);
  19.    
  20.     if(socket_desc < 0){
  21.         printf("Error while creating socket\n");
  22.         return -1;
  23.     }
  24.     printf("Socket created successfully\n");
  25.    
  26.     // Set port and IP:
  27.     server_addr.sin_family = AF_INET;
  28.     server_addr.sin_port = htons(2000);
  29.     server_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
  30.    
  31.     // Bind to the set port and IP:
  32.     if(bind(socket_desc, (struct sockaddr*)&server_addr, sizeof(server_addr))<0){
  33.         printf("Couldn't bind to the port\n");
  34.         return -1;
  35.     }
  36.     printf("Done with binding\n");
  37.    
  38.     // Listen for clients:
  39.     if(listen(socket_desc, 1) < 0){
  40.         printf("Error while listening\n");
  41.         return -1;
  42.     }
  43.     printf("\nListening for incoming connections.....\n");
  44.    
  45.     // Accept an incoming connection:
  46.     client_size = sizeof(client_addr);
  47.     client_sock = accept(socket_desc, (struct sockaddr*)&client_addr, &client_size);
  48.    
  49.     if (client_sock < 0){
  50.         printf("Can't accept\n");
  51.         return -1;
  52.     }
  53.     //printf("Client connected at IP: %s and port: %i\n", inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port));
  54.     printf("Connection accepted\n");
  55.     n=recv(client_sock,rcv,100,0);
  56.     rcv[n]='\0';
  57.     fp=fopen(rcv,"r");
  58.     if(fp==NULL)
  59.     {
  60.                 send(client_sock,"error",5,0);
  61.                 close(client_sock);
  62.     }
  63.     else
  64.     {
  65.         while(fgets(fileread,sizeof(fileread),fp))
  66.         {
  67.             if(send(client_sock,fileread,sizeof(fileread),0)<0)
  68.             {
  69.                 printf("Can't send file contents\n");
  70.             }
  71.             sleep(1);
  72.         }
  73.         if(!fgets(fileread,sizeof(fileread),fp))
  74.         {
  75.             printf("Done..");
  76.             send(client_sock,"completed",9,0);
  77.         }
  78.     }
  79.    
  80.     // Closing the socket:
  81.     close(client_sock);
  82.     close(socket_desc);
  83.    
  84.     return 0;
  85. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement