如何限制.NET中StreamReader.ReadLine()读取的字符数?
我正在用 C# 编写一个 Web 服务器应用程序,并使用 StreamReader 类从底层 NetworkStream 读取数据:
NetworkStream ns = new NetworkStream(clientSocket);
StreamReader sr = new StreamReader(ns);
String request = sr.ReadLine();
此代码很容易受到 DoS 攻击,因为如果攻击者从不断开连接,我们将永远无法读完该行。 有没有办法限制.NET中StreamReader.ReadLine()读取的字符数?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您必须使用 Read(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.For a slightly lazy version (that uses the single-characted reading version):
您可能需要
StreamReader.Read
重载之一:取自 http://msdn.microsoft.com/en-us/library/9kstw824.aspx
重点关注
sr.Read(c, 0, c.Length)
行。 这仅从流中读取 5 个字符并将其放入c
数组中。 您可能需要将 5 更改为您想要的值。You might need one of
StreamReader.Read
overload:Taken from http://msdn.microsoft.com/en-us/library/9kstw824.aspx
Focus on the
sr.Read(c, 0, c.Length)
line. This reads only 5 character from stream and put in intoc
array. You may want to change 5 to value you want.这是我自己的解决方案,基于 Marc Gravell 的解决方案:
这段代码“按原样”提供,没有任何保证。
Here is my own solution based on the solution by Marc Gravell:
This piece of code is provided "AS IS" with NO WARRANTY.
您始终可以使用“.Read(...)”,并且 MSDN 建议针对像您这样的情况这样做。
http://msdn.microsoft.com/en-us/library/system.io。 Streamreader.readline.aspx
You can always use ".Read(...)" and MSDN recommends doing so for a situation like yours.
http://msdn.microsoft.com/en-us/library/system.io.streamreader.readline.aspx