我在我们的软件中有一个错误,当我收到连接超时时发生。这些错误是非常罕见的(通常是当我的连接被我们的内部网络丢弃时)。我怎样才能人为地产生这种效果来测试我们的软件呢?

如果重要,应用程序是用c++ /MFC编写的,使用CAsyncSocket类。

编辑:

我尝试使用一个不存在的主机,我得到套接字错误:

无效的参数

我的下一个尝试是使用Alexander的建议,连接到不同的端口,例如81(在我自己的服务器上)。这很有效。与断开连接完全相同(等待60秒,然后出错)。谢谢你!


当前回答

Depending on what firewall software you have installed/available, you should be able to block the outgoing port and depending on how your firewall is setup it should just drop the connection request packet. No connection request, no connection, timeout ensues. This would probably work better if it was implemented at a router level (they tend to drop packets instead of sending resets, or whatever the equivalent is for the situation) but there's bound to be a software package that'd do the trick too.

其他回答

下面的URL总是给出一个超时,并结合了@Alexander和@Emu上面最好的答案:

http://example.com:81

使用example.com:81是对Alexander的答案的改进,因为example.com是由DNS标准保留的,因此它将始终不可访问,不像google.com:81,如果谷歌感觉像它,它可能会改变。此外,由于example.com被定义为不可访问,因此不会使谷歌的服务器超载。

我想说这比@emu的答案有进步,因为它更容易记住。

您可以尝试在外部端口(例如200)上连接到一个知名的Web站点。大多数防火墙都在DROP模式下工作,它会为你模拟超时。

您可以使用Python REPL来模拟接收数据时的超时(即在连接成功建立之后)。只需要一个标准的Python安装。

Python 2.7.4 (default, Apr  6 2013, 19:54:46) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import socket
>>> s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)        
>>> s.bind(('localhost', 9000))
>>> s.listen(0)
>>> (clientsocket, address) = s.accept()

现在它等待一个传入连接。将您想要测试的任何东西连接到localhost:9000。当你这样做时,Python将接受连接,accept()将返回它。除非您通过客户端套接字发送任何数据,否则调用方的套接字应该在下一次recv()期间超时。

有一些可用的服务允许您通过调用API(在其中指定服务器响应所需的时间)来人为地创建原始超时。macgyver上的Server Timeout就是这样一个服务的例子。

例如,如果您想测试一个需要15秒响应的请求,您只需向macgyver API发送一个post请求。

JSON载荷:

{
    "timeout_length": 15000
}

API响应(15秒后):

{
    "response": "ok"
}

macgyver上的服务器超时程序 https://askmacgyver.com/explore/program/server-timeout/3U4s6g6u

我想提醒大家注意mitmproxy。

通过配置(取自他们的示例)200:b@100:dr,您将获得一个随机断开的连接。