DarK_FirefoX DarK_FirefoX - 7 days ago 7
C Question

How to handle recv() returning -1 from Browser on HTTP Server?

I am writing a small HTTP server on C, using select() and non-blocking sockets, but I have found myself with an issue.

When I accept a connection and try to read the HTTP Request (from a BROWSER, i.e: Mozilla Firefox) using the recv() function with 1024 length buffer. I get the whole request just fine. But in a general way, I don't know if recv() gave me the whole request or piece of it, meaning I don't know if I should keep reading or send a HTTP Response back to the client (BROWSER). What happens is as follows:


  • I use recv(), so i get X bytes. (X could be less or equal to length of te request)

  • I need to KNOW if there are more bytes or not to be read. So i check the return value of recv(). I´ve been debugging, and ultimately it returns the whole request on one recv() operation, but i am not sure if I should rely on that, that´s why I am concern.

  • If the recv() operation where to return 0, it means the connection has been closed (shutdown), but BROWSER using persistent-connection won´t close the connection until recieving a HTTP Response.

  • Therefore, recv returns -1 and errno is set to EAGAIN/EWOULDBLOCK.



My question is, how to handle this case:

Will errno be set to EAGAIN/EWOULDBLOCK if the recv() function only read a piece of the request, or only if it has reached the end of the request and there is no more to be read?
How to handle that?

Thank you in advance
PS: I hope I´ve explained myself good enough so you can understand and try to help me.

EJP EJP
Answer

Will errno be set to EAGAIN/EWOULDBLOCK if the recv() function only read a piece of the request, or only if it has reached the end of the request and there is no more to be read? How to handle that?

Neither. It will be set to that value if there is no more data immediately available to be read. recv() doesn't know the HTTP request format from third base.

You need a good knowledge of RFC 2616 and friends to implement HTTP, specifically the parts about content-length and chunked encoding. You cannot do without it.

Comments