Thread: File contents printing with filename and saving with filename whenever i try to send

  1. #1
    Registered User
    Join Date
    Dec 2014
    Location
    Islamabad, Pakistan, Pakistan
    Posts
    2

    File contents printing with filename and saving with filename whenever i try to send

    I am trying to establish a connection between client and server to send a file to the server from a client. I have been successfully able to send files to the server but i am facing a problem with the the filename whenever i try to send any string to the server and use it in naming the filename at the server side, the string is successfully concatenated but it saves the filecontents in the filename. I have been pulling my hair out for this problem but couldn't reach a solution


    for example:
    i am sending a file hello1.txt to server and the server has to save it as abcxyz.txt as i am sending the "xyz" from the client. BUT Whenever i am doing this ,the file saves as abcxyzfilecontents.txt
    If i saved in the .txt file "you123" ,my file at server side would save as abcxyzyou123.txt


















    Here are my codes:




    Know that the server code implements a multi threaded server. The functionality to be discussed is defined in myfunc
    Code:
    server.c:
    
    
    #include <stdlib.h>
    #include <stdio.h>
    #include <errno.h>
    #include <string.h>
    #include <sys/types.h>
    #include <netinet/in.h>
    #include <sys/wait.h>
    #include <sys/socket.h>
    #include <signal.h>
    #include <ctype.h>          
    #include <arpa/inet.h>
    #include <netdb.h>
    # include<pthread.h>
    //#define PORT 20000 
    #define BACKLOG 5
    #define LENGTH 1024 
    int f=1;
    
    
    void error(const char *msg)
    {
        perror(msg);
        exit(1);
    }
    void *myfunc(void *recvsocket);
    //void *myfunc2(void *recvsocket2)
    
    
    int main(int argc, char *argv[])
    {
        int sockfd,newsockfd,portno;
        socklen_t clilen;
        char buffer[32];
        struct sockaddr_in serv_addr,cli_addr;
        int n;
          int num1,num2,sum;
    char revbuf[LENGTH];
          pthread_t threadid;
        
        if(argc<2)
        {
            fprintf(stderr,"No port number provided\n");
            exit(1);
        }    
        
        sockfd=socket(AF_INET,SOCK_STREAM,0);
        if(sockfd<0)
            error("ERROR opning socket");
        bzero((char *)&serv_addr,sizeof(serv_addr));
        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)
            error("error on binding");
        listen(sockfd,5);
        clilen=sizeof(cli_addr);
            //int c=80;   
    while(1)
    {
    newsockfd=accept(sockfd,(struct sockaddr *)&cli_addr,&clilen);
    int a=pthread_create(&threadid,NULL,myfunc,(void *)newsockfd);
    
    
    pthread_detach(threadid);
    sched_yield();
    
    
    }
    }
    void *myfunc(void *recvsocket)
    {
    int tempsock=(int *)recvsocket;
    char revbuf[LENGTH];
    char test[1024]={0};
    char filename[1024] = "/home/tabk/Desktop/texts/abc";
    f=f+1;
    bzero(revbuf,1024);
    char sockbuf[LENGTH];
    int m=read(tempsock,sockbuf,sizeof(sockbuf));
    
    
    sprintf(test,"%s",revbuf);
    
    
    strcat(filename,sockbuf);
    
    
    bzero(revbuf,LENGTH);
    
    
    sprintf(revbuf,"%ld",f);
    
    
    strcat(filename,revbuf);
    
    
    char ext[1024]=".txt";
    
    
    strcat(filename,ext);
    
    
    printf("\nourfilename:%s",filename);        
    
    
    char* fr_name=filename;
    
    
    FILE *fr = fopen(fr_name, "a");
            if(fr == NULL)
                printf("File %s Cannot be opened file on server.\n", fr_name);
            else
            {
                bzero(revbuf, LENGTH); 
                int fr_block_sz = 0;
                while((fr_block_sz = recv(tempsock, revbuf, LENGTH, 0)) > 0) 
                {
                    int write_sz = fwrite(revbuf, sizeof(char), fr_block_sz, fr);
                    if(write_sz < fr_block_sz)
                    {
                        error("File write failed on server.\n");
                    }
                    bzero(revbuf, LENGTH);
                    if (fr_block_sz == 0 || fr_block_sz != 1024) 
                    {
                        break;
                    }
                }
                if(fr_block_sz < 0)
                {
                    if (errno == EAGAIN)
                    {
                        printf("recv() timed out.\n");
                    }
                    else
                    {
                        fprintf(stderr, "recv() failed due to errno = %d\n", errno);
                        exit(1);
                    }
                }
                printf("\nOk received from client!\n");
                fclose(fr); 
            
    
    
                close(tempsock);
                printf("\n[Server] Connection with Client closed. Server will wait now...\n");
                while(waitpid(-1, NULL, WNOHANG) > 0);
            //}
        }
    
    
    }
    
    
    
    
    
    
    
    
    Client.c:
    #include <stdlib.h>
    #include <stdio.h>
    #include <errno.h>
    #include <string.h>
    #include <sys/types.h>
    #include <netinet/in.h>
    #include <sys/wait.h>
    #include <sys/socket.h>
    #include <signal.h>
    #include <ctype.h>          
    #include <arpa/inet.h>
    #include <netdb.h>
    #define LENGTH 1024
    void error(const char *msg)    
    {
        perror(msg);
        exit(0);
    }
    int main(int argc, char *argv[])
    {
        int sockfd,portno,n,s;
        struct sockaddr_in serv_addr;
        struct hostent *server;
        char buffer[32];
            char sdbuf[LENGTH]; 
            int f;
        char revbuf[LENGTH];
        if(argc<3)
        {
            fprintf(stderr,"usage %s hostname port\n",argv[0]);
            exit(0);
        }
    
    
        portno=atoi(argv[2]);
        sockfd=socket(AF_INET,SOCK_STREAM,0);
        if(sockfd<0)
            error("ERROR opning socket");
        server=gethostbyname(argv[1]);
        if(server==NULL)
        {
            fprintf(stderr,"ERROR, no such host\n");
            exit(0);
        }
        bzero((char *)&serv_addr,sizeof(serv_addr));
        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)
            error("Errror Connecting");
    /* Send File to Server */
    char fr_name[1024];
    printf("\nPlease provide path");
    scanf("%s",fr_name);
    printf("\nclientfilename:%s",fr_name);
    strcpy(sdbuf,"abc");
    n=write(sockfd,sdbuf,strlen(sdbuf));
    if(n<0)
    error("Error writing to socket");
    
    
    char* filename=fr_name;
     
                    printf("\n[Client] Sending %s to the Server... ", filename);
            FILE *fs = fopen(filename, "r");
            if(fs == NULL)
            {
                printf("ERROR: File %s not found.\n", filename);
                exit(1);
            }
    
    
            bzero(sdbuf, LENGTH); 
            int fs_block_sz; 
            while((fs_block_sz = fread(sdbuf, sizeof(char), LENGTH, fs)) > 0)
            {
                if(send(sockfd, sdbuf, fs_block_sz, 0) < 0)
                {
                    fprintf(stderr, "ERROR: Failed to send file %s. (errno = %d)\n", filename, errno);
                    break;
                }
                bzero(sdbuf, LENGTH);
            }
            printf("Ok File %s from Client was Sent!\n", filename);
        
    
    
            close (sockfd);
        printf("[Client] Connection lost.\n");
        return (0);
    }


    Result of terminal at server side:
    imgur: the simple image sharere
    At client side:
    imgur: the simple image sharer

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,666
    You have a serious misunderstanding of how send/recv (or write/read) actually work.

    > strcpy(sdbuf,"abc");
    > n=write(sockfd,sdbuf,strlen(sdbuf));
    > if(n<0)
    First off, never assume that n < 0 is the only failure. It's the only hard failure for sure, but there are plenty of soft failures.
    You may ask to send 3 bytes, but it's perfectly valid for write to return say 1 or 2 (as well as 3). This you have to code for, and perform retries on the remaining data until all is sent.

    The second big problem for you is that there is no framing information in your data stream.

    How is the receiver supposed to know that your filename prefix is only 3 bytes?

    If you wrote "abc\0" and then the content of the file, then the receiver would know to look out for the \0, extract your filename prefix, and know that the rest of the message(s) comprise the content of the file.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. File i/o filename its extension
    By Alix in forum C Programming
    Replies: 13
    Last Post: 01-17-2012, 06:04 PM
  2. Replies: 12
    Last Post: 09-04-2007, 11:44 AM
  3. Replies: 6
    Last Post: 04-11-2006, 04:52 PM
  4. getting filename from a file pointer
    By Unregistered in forum C Programming
    Replies: 10
    Last Post: 05-16-2002, 07:59 PM
  5. getting a file's path and filename
    By face_master in forum Windows Programming
    Replies: 4
    Last Post: 02-05-2002, 01:44 PM