glen4096
glen4096

Reputation: 874

How do you send a file via HTTP over tcp sockets in C?

I am implementing a client and server in C (on linux) and i want to send a text file to a server from the client using an HTTP PUT message.

I'm not really sure how to do this. Do I first send the HTTP request and header line over the socket, and then send the file over the socket piece by piece using a buffer? or do I need to prepend every piece of the text file with its own HTTP request and header line before I send them over?

I also read about this function called sendfile that seems like it would make this easier, but I wasn't sure how I would prepend an HTTP header and request line to the file if sendfile just sends the file straight to the socket.

Thank you for your help.

Upvotes: 4

Views: 2235

Answers (2)

n. m. could be an AI
n. m. could be an AI

Reputation: 119847

Do I first send the HTTP request and header line over the socket, and then send the file over the socket piece by piece using a buffer?

Yes.

or do I need to prepend every piece of the text file with its own HTTP request and header line before I send them over?

No.

I also read about this function called sendfile that seems like it would make this easier, but I wasn't sure how I would prepend an HTTP header and request line to the file if sendfile just sends the file straight to the socket.

First send the header with a normal send, then call sendfile. However you should read the documentation, which says

Note that a successful call to sendfile() may write fewer bytes than requested; the caller should be prepared to retry the call if there were unsent bytes.

This means that your life is not that much easier with sendfile. It is more efficient than a combination of read and write, but the amount of work the programmer needs to do is similar in both cases.

Upvotes: 7

milevyo
milevyo

Reputation: 2180

if you want to implement HTTP transmission protocol then check this RFC http://www.w3.org/Protocols/rfc2616/rfc2616-sec8.html#sec8.2.2

else if you want your own easy method then you can for example implement an API such DWORD(cmdPut)+filename+'\0'+DWORD(fileLen)+fileBinaryData.

Upvotes: 0

Related Questions