我遇到这样的情况:我使用 BufferedReader readLine()
从套接字读取数据,但 readline()
读取数据直到找到新行字符/回车符在数据中。
如果我的数据不包含换行符,那么它将继续读取数据,直到找到新行,并且入侵者可以注入(inject) DOS 攻击。
甚至套接字也会超时。
我知道一种解决方案可能是我们需要限制行大小并只读取一些数据,然后将数据附加到缓冲区。
这是最佳解决方案还是我可以通过其他方式做到这一点?
我可以重写 BufferedReader 并重写 readLine() 方法。这是可行的解决方案吗?
最佳答案
使用Socket.setSoTimeout(int)
转自javadoc
Enable/disable SO_TIMEOUT with the specified timeout, in milliseconds. With this option set to a non-zero timeout, a read() call on the InputStream associated with this Socket will block for only this amount of time.
If the timeout expires, a java.net.SocketTimeoutException is raised, though the Socket is still valid. The option must be enabled prior to entering the blocking operation to have effect. The timeout must be > 0. A timeout of zero is interpreted as an infinite timeout.
另请注意,从这一行开始
The option must be enabled prior to entering the blocking operation to have effect.
在执行read
操作之前,您必须调用Socket.setSoTimeout(int)
。
关于java - 如何防止Java中BufferedReader readLine()方法的Dos攻击?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6394529/