c# - 如何限制 .NET 中 StreamReader.ReadLine() 读取的字符数?

标签 c# readline streamreader ddos

我正在用 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/

相关文章:

.net - 从Windows SMTP服务读取EML文件。有什么理由不使用StreamReader?

c# - StreamReader 不读取回车符

c# - .NET Core 项目与 .NET Framework 中为 System.Data.DataTable 生成的 JSON 的变化

python - 在 Python 中读取文件时忽略行

c# - LocalService 的 'Access is denied' 的解决方法

python - codecs.open(utf-8) 无法读取纯 ASCII 文件

c# - ReadLine() 与 Read() 有效获取 CR 和 LF?

c# - 使用 streamreader/streamwriter 在 C# 中逐行写入文件非常慢

c# - 获取给定 UserPrincipal 的组列表

c# - 将数据从 MySQL 数据库加载到 C# DGV