Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

http

tcp

sockets

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.

like image 262
glen4096 Avatar asked Oct 19 '25 10:10

glen4096


1 Answers

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.

like image 197
n. 1.8e9-where's-my-share m. Avatar answered Oct 22 '25 01:10

n. 1.8e9-where's-my-share m.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!