3

I'm trying to implement a basic file server. I have been trying to use the sendfile command found here: http://linux.die.net/man/2/sendfile I'm using TCP.

I can have it send fine, but its sending in binary and I'm not sure if thats the hang up.

I am trying to receive the file with recv, but it isn't coming through correctly. Is there a special way to receive a binary file, and put it into a string?

EDIT: Asked to supply some code, here it is:

SENDFILE Call (from Server process)

FILE * file = fopen(filename,"rb");
    if ( file != NULL)   
    {            
        /*FILE EXISITS*/ 
        //Get file size (which is why we opened in binary)
        fseek(file, 0L, SEEK_END);
        int sz = ftell(file);
        fseek(file,0L,SEEK_SET);

        //Send the file
        sendfile(fd,(int)file,0,sz);
        //Cleanup 
        fclose(file);
    }

RECIEVE Call (from Client process, even more basic than a loop, just want a single letter)

//recieve file
    char fileBuffer[1000];
    recv(sockfd,fileBuffer,1,0);
    fprintf(stderr,"\nContents:\n");
    fprintf(stderr,"%c",fileBuffer[0]);

EDIT: wrote some code for checking return values. sendfile is giving errno 9 - bad file number. Which im assuming is at my second file descriptor in the call (the one for the file i'm sending). I cast it as an int because sendfile was complaining it wasn't an int.

How should I use send file given the file pointer code I have used above in th sendfile call?

user974703
  • 1,653
  • 4
  • 20
  • 27
  • 1
    Can you supply some code, your sendfile call and your recv-loop? – ott-- Oct 01 '11 at 18:42
  • Always, always, always check the return value of your system calls (fseek, sendfile, recv). And include the result(s) in your question. – Nemo Oct 01 '11 at 19:12

2 Answers2

3

You cannot use sendfile() with a FILE*, you need a file descriptor as given by open(), close() and friends. You cannot just cast a FILE* into an int and thinking it would work.

Maybe you should read the sendfile() manpage for more information.

BatchyX
  • 4,986
  • 2
  • 18
  • 17
1

There is no special way. You just receive with read() or recv().

Probably, you've got your receiving code wrong.

jpalecek
  • 47,058
  • 7
  • 102
  • 144
  • so if I were to recv into a string, everything should turn out fine? – user974703 Oct 01 '11 at 18:45
  • depends on how you do it. Don't expect any socket reading code to read whole file at once, though. Especially if it is big. – jpalecek Oct 01 '11 at 18:49
  • Yea, i have it in a loop. But even if i could get the first few letters to know it was reading right. I'll have a look at it soon. – user974703 Oct 01 '11 at 18:56