如何限制由StreamReader.ReadLine()在.NET中读取的字符数? [英] How to limit the number of characters read by StreamReader.ReadLine() in .NET?

查看:812
本文介绍了如何限制由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();
        }                
    }
}

这篇关于如何限制由StreamReader.ReadLine()在.NET中读取的字符数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆