如何限制.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)
您可能需要 StreamReader.Read
重载之一:
取自 http://msdn.microsoft.com/en-us/library/9kstw824.aspx
using (StreamReader sr = new StreamReader(path))
{
//This is an arbitrary size for this example.
char[] c = null;
while (sr.Peek() >= 0)
{
c = new char[5];
sr.Read(c, 0, c.Length);
//The output will look odd, because
//only five characters are read at a time.
Console.WriteLine(c);
}
}
重点关注 sr.Read(c, 0, c.Length)
行。 这仅从流中读取 5 个字符并将其放入 c
数组中。 您可能需要将 5 更改为您想要的值。
这是我自己的解决方案,基于 Marc Gravell 的解决方案:
using System;
using System.IO;
using System.Text;
namespace MyProject
{
class StreamReaderExt : StreamReader
{
public StreamReaderExt(Stream s, Encoding e) : base(s, e)
{
}
/// <summary>
/// Reads a line of characters terminated by CR+LF from the current stream and returns the data as a string
/// </summary>
/// <param name="maxLineLength">Maximum allowed line length</param>
/// <exception cref="System.IO.IOException" />
/// <exception cref="System.InvalidOperationException">When string read by this method exceeds the maximum allowed line length</exception>
/// <returns></returns>
public string ReadLineCRLF(int maxLineLength)
{
StringBuilder currentLine = new StringBuilder(maxLineLength);
int i;
bool foundCR = false;
bool readData = false;
while ((i = Read()) > 0)
{
readData = true;
char c = (char)i;
if (foundCR)
{
if (c == '\r')
{
// If CR was found before , and the next character is also CR,
// adding previously skipped CR to the result string
currentLine.Append('\r');
continue;
}
else if (c == '\n')
{
// LF found, finished reading the string
return currentLine.ToString();
}
else
{
// If CR was found before , but the next character is not LF,
// adding previously skipped CR to the result string
currentLine.Append('\r');
foundCR = false;
}
}
else // CR not found
{
if (c == '\r')
{
foundCR = true;
continue;
}
}
currentLine.Append((char)c);
if (currentLine.Length > maxLineLength)
{
throw new InvalidOperationException("Max line length exceeded");
}
}
if (foundCR)
{
// If CR was found before, and the end of the stream has been reached, appending the skipped CR character
currentLine.Append('\r');
}
if (readData)
{
return currentLine.ToString();
}
// End of the stream reached
return null;
}
}
}
这段代码“按原样”提供,没有任何保证。
您始终可以使用“.Read(...)”,并且 MSDN 建议针对像您这样的情况这样做。
http://msdn.microsoft.com/en-us/library/system.io。 Streamreader.readline.aspx
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
您必须使用 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):