I was looking at this example on how to read Proxy Protocol headers. There’s some code that magically reads the exact amount of bytes required every time. I built the examples and it works without fail. To me it seems like a naive approach, yet it works fine and has blown a hole in my understanding of how reading from streams works. Here is the code in question,
The loop can definitely end up reading too many bytes. Can you give more info as to how you are observing it not reading too far? Are you sure that the client is sending any bytes beyond the ones parsed by your loop?
If you have a look here, it shows how to setup a server and a proxy. Using curl, you send a request to the proxy which prepends the proxy protocol header and forwards it to the server.
If you add some http parsing logic to the handle_connection function above, it will successfully parse the request bytes every time.
I agree that it could and should read too many bytes when done this way.
If the sender uses multiple calls to write they will probably end up on different packets. If you send head and body in a single write then you may over-read when getting the header. Get a dump of what packets are transmitted to see. (eg use wireshark)