如何限制由StreamReader.ReadLine()在.NET中读取的字符数?
我写在C#中的Web服务器应用程序,并使用StreamReader类从底层的NetworkStream阅读:
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();
这代码很容易受到DoS攻击,因为如果攻击者从未断开,我们永远不会读完行。有什么办法来限制StreamReader.ReadLine()在.NET中读取的字符数?
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?
您将不得不使用读(的char [],INT,INT)
过载(这不限制长度),做你自己最终的在线检测; 。应该不会太棘手
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.
有关一个稍微懒版本(即使用单characted阅读版):
For a slightly lazy version (that uses the single-characted reading version):
static IEnumerable<string> ReadLines(string path, int maxLineLength)
{
StringBuilder currentLine = new StringBuilder(maxLineLength);
using (var reader = File.OpenText(path))
{
int i;
while((i = reader.Read()) > 0) {
char c = (char) i;
if(c == '\r' || c == '\n') {
yield return currentLine.ToString();
currentLine.Length = 0;
continue;
}
currentLine.Append((char)c);
if (currentLine.Length > maxLineLength)
{
throw new InvalidOperationException("Max length exceeded");
}
}
if (currentLine.Length > 0)
{
yield return currentLine.ToString();
}
}
}