0

所以这是我的大学项目,变量的使用效率不是一个大问题。程序是Unix环境下基于Socket网络编程的“FTP-文件传输” !该程序仅响应一项服务。

该程序可让您将文件从客户端下载到服务器并从服务器下载到客户端!我的代码正在使用验证进行上写,但是当我尝试无限循环服务器的执行时会出现问题,因为每次执行时都重新启动服务器是没有意义的!

谁能建议我逻辑错误发生在哪里?

服务器端:

#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>     
#include<sys/socket.h>
#include<netinet/in.h>
#include<string.h>
#include<errno.h>
#include<unistd.h> 


    int sockfd,newsockfd,portno,clien;
    char buffer[256] = { '\0' };
    struct sockaddr_in serv_addr,cli_addr;
    int n;
    int download();
    void upload();
    void server_files();
    void authentication();
    int main(int argc, char *argv[])
    {


    if(argc<2)
    {
        fprintf(stderr,"Error, No port provided\n");
        exit(1);
    }

    sockfd=socket(AF_INET,SOCK_STREAM,0);

    if(sockfd<0)
    {
        printf("Error opening socket\n");
        exit(1);
    }

    bzero((char *) &serv_addr, sizeof(serv_addr));//zeroing the sturture

    portno =atoi(argv[1]);

    serv_addr.sin_family=AF_INET;
    serv_addr.sin_addr.s_addr=INADDR_ANY;
    serv_addr.sin_port=htons(portno);

    if(bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) <0 )
    {
        printf("Error on binding\n");
        exit(1);
    }

    int optval;
    setsockopt(100,sockfd, SO_REUSEADDR, &optval, sizeof optval);


    listen(sockfd,5);
    clien = sizeof(cli_addr);

    while(1)
    {
    newsockfd=accept(sockfd, (struct sockaddr *) &cli_addr, &clien );


    if(newsockfd <0)
    {   
        printf("Error on accept\n");
        exit(1);
    }   


    //Authentication
    char auth[2];
    read(newsockfd,auth,2);
    int x = atoi(auth);
    if(x==0)
    {
        char user[20]={ '\0' } ;
        char pass[20]={ '\0' } ;


        read(newsockfd,user,20);
        usleep(1000);
        read(newsockfd,pass,20);

        if((strcmp(pass,"123") != 0) && (strcmp(user, "tuhin") != 0))
            {
            char auth[2]="1";
            write(newsockfd,auth,2);
            close(newsockfd);
            exit(0);    
        }else{
            char auth[2]="0";
                write(newsockfd,auth,2);
        }

    }
    //End OF Authentication

    //Server NAME
    char S_name[15]="ftp_C-project.";
    usleep(1000);
    write(newsockfd,S_name,15);

    //check Id from client
    system("clear");
    char id[2];
    read(newsockfd,id,2);
    int ch = atoi(id);
    switch(ch)
    {

        case 1:download();
        break;

        case 2:upload();
        break;

        case 3:server_files();
        break;

        case 4:printf("\nDisplayed file contents of Client\n\n");
        break;

        default:printf("Invalid\n");
    }
}//END OF WHILE(1)
    return 0;
}



    int download()
    {
        char buffer[256] = {'\0'};  
        n=read(newsockfd,buffer,256);
        if(n<0){
        printf("Error reading from socket\n");
        exit(1);
    }

    n=access(buffer,F_OK); // Check for validation of file
    switch(n)
    {
    case 0:
        {
        //sends value 0 to char error of client, "File present"
        char id[2]="0";
        write(newsockfd,id,2);

            printf("Client connected successfully\n");
        printf("\nFile requested by the client : %s \n\n", buffer);

        char buf[256] = {'\0'};
        FILE *fp;
        fp = fopen(buffer, "r");
            if(fp == NULL)
            {
                printf("fopen failed : %s \n", strerror(errno));
                return -1;
            }else
            {
                printf("Open of file \"%s\" is successful \n", buffer);
        }

        while(fgets(buf, sizeof(buf), fp) != NULL)
        {
            //printf("printing line from the file : %s \n", buf);
            write(newsockfd, buf, sizeof(buf));
        }
        printf("\nFile Transfer Completed.\n");
        }

    case-1:
        {
        char id[2]="-1";
        write(newsockfd,id,2);
        printf("Download process terminated.\n");
        }
    }
}




    void upload()
    {
        char buffer[256] = {'\0'};  

    // error will store -1 || 0
      char error[256];
      read(newsockfd, error, 256);
      int ch =atoi(error);

    if(ch==0)
    {   
        n=read(newsockfd,buffer,256);
        if(n<0){
        printf("Error reading from socket\n");
        exit(1);
        }

        char mybuf[256];
            FILE *fp = fopen(buffer, "a+");

            while(1)
        {
            n = read(newsockfd, mybuf, sizeof(mybuf));
             if (n <= 0)
            break;
            fputs(mybuf, fp);  
        } 
        printf("\nFile requested by the client to upload: %s \n", buffer);
        printf("\nUpload Complete\n");

    }
    else
    printf("Upload process terminated.\n");
    }


    void server_files()
    {
        char buffer[256] = {'\0'};  
        system("ls -l>_");

        char buf[256] = {'\0'};
        FILE *fp = fopen("_", "r");
        while(fgets(buf, sizeof(buf), fp) != NULL)
        {

        write(newsockfd, buf, sizeof(buf));

        }
        system("rm _");
        printf("\nSent file contents of the Server to Client\n");
    }

客户端:

#include<stdio.h>  
 #include<stdlib.h>  
 #include<sys/types.h>     
 #include<sys/socket.h>  
 #include<netinet/in.h>  
 #include<netdb.h>  
 #include<string.h>  
 #include<unistd.h> 
 #include<errno.h>

    void client_files();
    void server_files();
    void download();
    int upload();

  int sockfd,portno,n,q;  
      char buffer[256] = {'\0'};  
      struct sockaddr_in serv_addr;  
      struct hostent *server; 

 int main(int argc, char *argv[])  
 {  

      if(argc<3)  
      {  
      fprintf(stderr,"Usage %s hostname port\n",argv[0]);  
 exit(1);  
      }  

      portno = atoi(argv[2]);       
      sockfd=socket(AF_INET,SOCK_STREAM,0);  

      if(sockfd<0)  
      {  
      printf("Error opening socket\n"); 
      exit(0);  
      }  

      bzero((char *) &serv_addr, sizeof(serv_addr));//zeroing the sturture  
      server=gethostbyname(argv[1]);  

      if(server==NULL){  
      fprintf(stderr,"Error, no such host\n");  
      exit(0);  
      }  

      serv_addr.sin_family=AF_INET;  
      bcopy((char *)server->h_addr,(char *)&serv_addr.sin_addr.s_addr,server->h_length);  

      serv_addr.sin_port=htons(portno);  

      if(connect(sockfd, (struct sockaddr*) &serv_addr,sizeof(serv_addr)) <0 )  
      {  
      printf("Error Connecting\n");  
      exit(0); 
      } 

      //Authentication
      system("clear");
      char id[2]="0";
    write(sockfd,id,strlen(id));
      char usr[20]={ '\0' } ;
      char pwsd[20]={ '\0' } ;
      char auth[256]={ '\0' } ;
      system("clear");  
      printf("Authentication!\n");

      printf("User :");
      scanf("%s",usr);
      write(sockfd,usr,strlen(usr));

      char *pswd =getpass("#");
      write(sockfd,pwsd,20);

     usleep(1000);
        read(sockfd,auth,2);
        int x=atoi(auth);
        if(x)
    {
        printf("Access Denied!\nWrong Credentials.\n");
        close(sockfd);
        exit(0);
        }
      //End OF Authentication

      //Fetch name of Server
      char S_name[15];
      system("clear");
        read(sockfd,S_name,15);
        sleep(1);
      printf("Server Name: %s\n",S_name);


      sleep(1);
        printf("\n>>>>Access Granted<<<<\n");
    sleep(1);
    printf("1.Download\n2.Upload\n");
    printf("3.List files (Server)\n4.List files (Client)\n");
    int ch;
    scanf("%d",&ch);
    switch(ch){
    case 1:download();
    break;
    case 2:upload();
    break;
    case 3:server_files();
    break;
    case 4:client_files();
    break;
    default:
    printf("Invalid Input\n");
    }
      return 0;  
 }  



    void download()
    {
    char buffer[256] = {'\0'};  
    char id[2]="1";
    write(sockfd,id,strlen(id));

    printf("Enter the filename to download from the server:");  
      scanf("%s", buffer);
      n=write(sockfd,buffer,strlen(buffer)); 
      if(n<0){  
      printf("Error writing to socket\n");  
      exit(0); 
      }  

        // error will store -1 || 0
      char error[256];
      read(sockfd, error, 256);
      int ch =atoi(error);
        switch(ch)
        {
      case 0://If file present on server
        {
        printf("Download Initialized \n");

            char mybuf[256];
             FILE *fp = fopen(buffer, "a+");

        while(1)
             {
                n = read(sockfd, mybuf, sizeof(mybuf));
                if (n <= 0)
                break;
            // printf("buf : %s \n", mybuf);
                fputs(mybuf, fp);  
        } 
        sleep(1);

        printf("\nDownload Completed \n\n");
        break;
        }

    case-1://If file not present on server
        printf("\nFile \"%s\" not found.\n",buffer);
        printf("Download process terminated.\n");
        break;
        }
    }



    int upload(){
    char buffer[256] = {'\0'};  
    char id[2]="2";
    write(sockfd,id,strlen(id)); 
    printf("Enter the filename to upload to the server:");  
      scanf("%s", buffer);

    n=access(buffer,F_OK);

    switch(n)
    {

    case 0:
        {
            char id[2]="0";
            write(sockfd,id,2);
            usleep(5000);
            n=write(sockfd,buffer,strlen(buffer));
            usleep(5000);
            if(n<0){  
            printf("Error writing to socket\n");  
            exit(0); 
            } 

            printf("Upload Initialized \n");

            char mybuf[256];
            memset(mybuf, '\0', sizeof(mybuf));
                FILE *fp = fopen(buffer, "r");
            if(fp == NULL)
             {
                    printf("fopen failed : %s \n", strerror(errno));
                    return -1;
                }
             else
                {
                    printf("Open of file \"%s\" is successful \n", buffer);
            }


            while(fgets(mybuf, sizeof(mybuf), fp) != NULL)
            {
                //printf("printing line from the file : %s \n", mybuf);
                write(sockfd, mybuf, sizeof(mybuf));
            }

            printf("\nFile Transfer Completed.\n");
            break;
        }

    case-1:
        {
            char id[2]="-1";
            write(sockfd,id,2);

            printf("\nFile \"%s\" not found.\n",buffer);
            printf("Upload process terminated.\n");
            break;
        }
    }
}

    void server_files(){
    char buffer[256] = {'\0'};  
    char id[2]="3";
    write(sockfd,id,strlen(id));
    int x=0;
    char mybuf[256];
    while(1)
     {
         n = read(sockfd, mybuf, sizeof(mybuf));
        if (n <= 0)
         break;
    if(x!=1){
     printf(" %s ", mybuf); 
    }
    x++;    
    }
     }  


    void client_files(){
    char buffer[256] = {'\0'};  
    char id[2]="4";
    write(sockfd,id,strlen(id));
    system("ls -l");
    }
4

1 回答 1

0

根据您粘贴的内容尚不清楚。您应该粘贴不起作用的确切代码。

但似乎你的while循环在接受之后开始,这是不对的。您需要调用accept()每个新连接:

while ((newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clien))  != -1) {
    /* ... */
}

您还必须close(newsockfd)在完成连接后调用,否则您将泄漏文件描述符。

此外,您确实意识到您现在的服务器一次只能服务一个连接。我假设是这样,但以防万一:)

注意:你真的不应该打电话给system(). 您应该使用 UNIX API,但这超出了您的问题范围。

于 2013-06-01T17:58:21.963 回答