0

I'm trying to figure out how to send a file from my server to the client using C. I'm very new at C, so not sure entirely how wrong I have it:

Snippet server:

while (1) { 
    len = sizeof(clientAddr); 
    sock = accept(serverSock, (struct sockaddr *) &clientAddr, &len);
    file = fopen(filename, "rb");
    while(!feof(file)) {
        int flen = fread(buffer, 1, sizeof(buffer), file);
        int sz = 0;
          while (sz < flen) {
            int sent = send(sock, &buffer[sz], flen-sz, 0);
            sz += sent;
          }
        printf("Sent file!");
     }
    fclose(file);
    close(sock);
}

Snippet from Client

int status = connect(sock, (struct sockaddr *)&Address, sizeof(Address));

int flen;
file = fopen(filename, "wb");
while(flen = recv(sock, buffer, sizeof(buffer), 0) > 0) {
    bzero(buffer, sizeof(buffer));
    fwrite(buffer,1, flen, file);
}

Basically, I'm getting an error of "Segmentation Fault (core dump)" from the server. Is there any guide on trying to do this? Any help is appreciated, thanks!

NandoAndes
  • 45
  • 1
  • 7
  • You should probably be checking that `file` is non-null before trying to use it. Also, this is a good opportunity to learn how to use a debugger to see exactly where and why you're getting the segmentation fault. – Jim Lewis Jan 21 '17 at 02:51
  • 1
    How is `buffer` defined? – alk Jan 21 '17 at 09:26
  • Your while statement should have another pair of parentheses. You are setting `flen` to the result of the comparison `recv(...) > 0)`. Not apparently what you intended. You probably want `while ((flen = recv(...)) > 0) {` which sets `flen` to the return value of `recv` and compares that with 0. (This doesn't explain your segmentation fault as far as I can tell.) – Gil Hamilton Jan 21 '17 at 18:54
  • Possible duplicate of [Send and Receive a file in socket programming in Linux with C/C++ (GCC/G++)](https://stackoverflow.com/questions/2014033/send-and-receive-a-file-in-socket-programming-in-linux-with-c-c-gcc-g) – Ciro Santilli OurBigBook.com Jun 15 '17 at 05:40

0 Answers0