sting
sting

Reputation: 13

C Socket server programming send file

I am currently running into trouble with C socket programming. I am required to use following curl command as client behavior to request file from server.

curl -v SERVER_ADDRESS --request-target FILENAME for sending from server

So far I am able to create the server, parse headers and handle the PUT request. But I am having trouble with GET request, which is sending file from server to client. My code won't create, open and write file on client. And here's the part I'm not able to solve.

    //cl is value returned by accept()
       fd = open(name, O_RDONLY);
       if (fd<0){
         write(cl, "HTTP/1.1 404 Not Found\r\n", sizeof("HTTP/1.1 404 Not Found\r\n"));
         close(cl);
       }
       else{
         contentLength = 0;
         temp = read(fd, newbuffer, 32768);
         while(temp>0){
           write(cl, newbuffer, temp);
           contentLength = contentLength+temp;
           temp = read(fd, newbuffer, 32768);
         }
      sprintf(message, "HTTP/1.1 200 OK\r\nContent-Length: %d", contentLength);
      strcat(message, "\r\n\r\n");
      write(cl, message, sizeof(message));

Helps are ppreciated.

Upvotes: 1

Views: 262

Answers (1)

Steffen Ullrich
Steffen Ullrich

Reputation: 123260

The HTTP header contains the status line and the header fields, including the Content-length of the body. The HTTP body must follow the header. But your code opens the file and writes the content immediately to the client and only after this is done you write the header. In other words: you write the body before the header instead of the body after the header.

Apart from that writing the header is wrong too: sizeof(message) is not the length of the message but the size of the buffer or pointer (not clear since there is no declaration of message in what you show).

Upvotes: 1

Related Questions