I am writing a web server application in C# and using StreamReader class to read from an underlying NetworkStream:
NetworkStream ns = new NetworkStream(clientSocket); StreamReader sr = new StreamReader(ns); String request = sr.ReadLine();
This code is prone to DoS attacks because if the attacker never disconnects we will never finish reading the line. Is there any way to limit the number of characters read by StreamReader.ReadLine() in .NET?
You would have to use the
Read(char[], int, int)overload (which does limit the length) and do your own end-of-line detection; shouldn’t be too tricky.For a slightly lazy version (that uses the single-characted reading version):