开发者

Sockets don't send all binary data

Actually I'm working on very simple FTP server. Now I have problem with sending file (RETR in FTP protocol). I'm using sockets and binary mode in my client. Files with text send perfectly, but problem is binary files (images etc.).

Here's piece of my code:

FILE *fin=fopen(fileloc,"rb");

if(fin != NULL){
    fpos_t filelen;

    fseek (fin, 0, SEEK_END);
    fgetpos (fin, &filelen);

    fseek (fin, 0, SEEK_SET);
    printf("Sending file %s (%d b)", fileloc, filelen);
    sprintf(sbuffer,"150 Opening BINARY mode data connection for file transfer.\r\n");
    bytes = send(ns, sbuffer, strlen(sbuffer), 0);
    byte temp_buffer[512];

    long int totalsent;
    totalsent = 0;

    while (!feof(fin)){

        memset(temp_buffer, '\0', sizeof(sbuffer));

        fgets((char *)temp_buffer, sizeof(sbuffer), fin);

        if (!active) bytes = send(ns_data, (char *)temp_buffer, strlen(sbuffer), 0);
        else bytes = send(s_data_act, (char *)temp_buffer, strlen(sbuffer), 0);

        totalsent = totalsent + bytes;

        printf("     file size = %d, send = %d bytes, strlen = %d, total = %d, left = %d\n",
               filelen, bytes, strlen(sbuffer), totalsent, filelen-totalsent);
        }

    fclose(fin);
    sprintf(sbuffer,"250 File transfer completed... \r\n");
    bytes = send(ns, sbuffer, strlen(sbuffer), 0);
}

My FTP client is getting incomp开发者_如何学运维lete files with differences inside (I open files with Notepad to compare), as you could see on this screen image if the URL worked without requiring a sign-in:

http://i53.tinypic.com/2wcjtdk.jpg

There is also differences in file size - original file is about 7kB and sent copy is about 1kB less. I used much different FTP client and there is the same problem.


In your send call you are using strlen which might work fine for text data but not for binary data. When you read from the file you need to use a call like read which will tell you how many bytes were actually read so you can send that many bytes in the send call.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜