-2

I trying to write a small code to send a file over network on Windows, but it seem not work properly. This is my code:

char *arrFile = readFile("test.exe");
int fileSize = getFileSize("test.exe");
int sentSize = 0;
int justSent;

while(sentSize < fileSize) {
    justSent = send(sock, arrFile + sentSize, fileSize - sentSize, 0);
    sentSize += justSent;
}

It got error at send function after several loops, I don't know why, Can someone tell me the reason (and solution of couse :D)?

Update

I'm using non-blocking socket and get 'WSAEWOULDBLOCK' error but it still don't send anything after error until client send back something :-(

Above code is C, but C++ as well :D

Bình Nguyên
  • 2,252
  • 6
  • 32
  • 47

1 Answers1

2

It looks like the function send is not working correctly. It is returning a -1, which is then added to justSent. After a few iterations, justSent is sufficiently negative to cause a segmentation fault.

To fix this issue, you should add code to handle the error condition (When send returns a value < 0).

Something like this would be a good start:

while(sentSize < fileSize) 
{
    justSent = send(sock, arrFile + sentSize, fileSize - sentSize, 0);
    if(justSent < 0)
    {
        printf("Error!\n");
        break;
    }
    sentSize += justSent;
}
charliehorse55
  • 1,940
  • 5
  • 24
  • 38