我正在用C#编写Web服务器应用程序,并使用StreamReader类从底层NetworkStream中读取:
NetworkStream ns = new NetworkStream(clientSocket); StreamReader sr = new StreamReader(ns); String request = sr.ReadLine();
此代码容易受到DoS攻击,因为如果攻击者永远不会断开连接,我们将永远不会读完该行.有没有办法限制.NET中StreamReader.ReadLine()读取的字符数?
您必须使用Read(char[], int, int)
过载(确实限制了长度)并进行自己的行尾检测; 不应该太棘手.
对于稍微懒惰的版本(使用单一阅读版本):
static IEnumerableReadLines(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(); } } }