我正在用 C# 编写 Web 服务器应用程序并使用 StreamReader 类从底层 NetworkStream 读取数据:
NetworkStream ns = new NetworkStream(clientSocket);
StreamReader sr = new StreamReader(ns);
String request = sr.ReadLine();
这段代码很容易受到 DoS 攻击,因为如果攻击者从不断开连接,我们将永远无法读完该行。有什么方法可以限制 StreamReader.ReadLine() 在 .NET 中读取的字符数吗?
最佳答案
您将不得不使用 Read(char[], int, int)
重载(它确实限制了长度)并进行您自己的行尾检测;不应该太棘手。
对于稍微懒惰的版本(使用单字阅读版本):
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();
}
}
}
关于c# - 如何限制 .NET 中 StreamReader.ReadLine() 读取的字符数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/400407/