ChatGPT解决这个技术问题 Extra ChatGPT

Artificially create a connection timeout error

I've had a bug in our software that occurs when I receive a connection timeout. These errors are very rare (usually when my connection gets dropped by our internal network). How can I generate this kind of effect artificially so I can test our software?

If it matters the app is written in C++/MFC using CAsyncSocket classes.

Edit:

I've tried using a non-existent host, and I get the socket error:

WSAEINVAL (10022) Invalid argument

My next attempt was to use Alexander's suggestion of connecting to a different port, e.g. 81 (on my own server though). That worked great. Exactly the same as a dropped connection (60 second wait, then error). Thank you!

Hi Mark, I tried solution that work for you but what I'm receiving is #503 (Service Unavailable.). Isn't should be one of these, #504 (Gateway Timeout), #599 (Network connect timeout error), #598 (Network read timeout error).
Do you want a connect timeout, or a read timeout?

e
emu

Connect to a non-routable IP address, such as 10.255.255.1.


Idem, and I guess this is a better answer since google.com:81 might be reachable one day.
... and because sending random packets to other people's servers from your unit tests is rude.
This won't always work. For instance, with Python's urllib, this will return a 'No route to host' exception. FYI
10.0.0.0 , 10.255.255.255, 172.16.0.0, 172.31.255.255, 192.168.0.0 ,192.168.255.255 all these are non-routable.
The "No route to host" error mentioned by @FHI generally appears in two conditions: (a) when you try connecting to a non-reachable host in your local LAN (meaning, it doesn't answer ARP queries so it's basically a "ARP timeout"). And (b) when a router returns the corresponding ICMP error. The first case happens if you are in the same subnet as the private IP you test. The second case if a router doesn't know how to route your packet to its destination, but in some cases they just drop the packet without sending the ICMP error.
A
Alexander

Connect to an existing host but to a port that is blocked by the firewall that simply drops TCP SYN packets. For example, www.google.com:81.


This answer is simple and works just like @emu's answer below. I understand this answer didn't intend to suggest using google.com:81 but the point here is to use a different port that is blocked. So you can always use :.
Unless its your own server, its rude to hit other servers for your testing. Use a civilized solution like the one emu mentioned below, by hitting a non-routable IP address like 10.255.255.1, or setup a virtual server of your own for testing purposes.
I think that Google may have blocked this port. When I test this with Chrome, I just "Server not available." When I use @emu's trick below, the connection hangs as expected. Am I missing something?
This will give a connection refused not timeout .
I agree with @zeeshan, we are living in a civilized world, instead of choking someone others server, we need to choke our own server.
D
Der_Meister

Plenty of good answers but the cleanest solution seems to be this service

https://httpstat.us/504?sleep=60000

You can configure the timeout duration (up to 230 seconds) and eventual return code.


this is exactly what I was looking for. Great service, will add it to my bookmarks
T
Tom Chamberlain

If you are on a unix machine, you can start a port listening using netcat:

nc -l 8099

Then, modify you service to call whatever it usually does to that port e.g. http://localhost:8099/some/sort/of/endpoint

Then, your service will open the connection and write data, but will never get a response, and so will give you a Read Time Out (rather than Connection Refused)


It's usefull since you can see whatever data your application is pushing. You could check if your application is asking for a response.
This is true for navigating to some sort of endpoint, as mentioned, but if I try to connect some other way it quickly gives a connection refused, which is not the behavior I am trying to mock right now.
@AlanSE - what other way do you mean? You can have anything after the port number; netcat won't care as it has nothing to handle any URLs
@TomChamberlain Oh wait, I might know what I was doing wrong. I am trying to simulate a ssh connection timeout. So I am giving it localhost, port 8099, but previously I didn't give a username, so if I just put in something ssh alanse@localhost -p 8099, it looks like that does it.
To test a connection timeout at the socket level, freeze the nc process with a kill -STOP <pid> (or just CTRL-Z it without putting in background). The system will act as if the server was running, but wait for the server to accept the connection, resulting in a connection timeout (errno 110).
s
speedplane

The following URL always gives a timeout, and combines the best of @Alexander and @Emu's answers above:

http://example.com:81

Using example.com:81 is an improvement on Alexander's answer because example.com is reserved by the DNS standard, so it will always be unreachable, unlike google.com:81, which may change if Google feels like it. Also, because example.com is defined to be unreachable, you won't be flooding Google's servers.

I'd say it's an improvement over @emu's answer because it's a lot easier to remember.


currently I see example.com resolving to 93.184.216.34, and actually serves a short HTML explaining it's an example domain... port 81 still doesn't respond.
The question is really whether example.com is supposed to be used in that way. Only if they make it officially free to be flooded with test packets is this domain better than any other commercial domain. Using domains for such purpose without permission is unethical, to say the least, if not illegal, because it's costing someone money to handle these packets. Consider using httpstat.us as @AndyTheEntity pointed out in his answer.
@Manuel You're missing the point... example.com is not a commercial domain, it's one of the few domain names that's explicitly specified as being unusable. No one can own example.com and DNS routers know that it never routes to a real address. So it's not costing anyone server time, there is nothing wrong with using it
@speedplane The IANA owns the domain by regulation and maintains a web server providing a web page explaining the purpose of example.com. There is infrastructure behind the domain, hence every request it is costing the IANA money. The permissible use is referenced in RFC 2606 and RFC 6761, you are not free to use the domains for whatever purpose you like, like flodding them instead of another server, as you mention. Your claim that example.com is defined to be unreachable is incorrect, it is reachable. Port 81 is unreachable now, but where is that defined to be guaranteed in the future?
The RFC you point to specifically allows for DNS testing. They recommend you use a .test top level domain, rather than example.com, but these domains were clearly setup for this purpose. Yes, it might cost the IANA a bit of money, but this is a service that they provide. Our DNS fees are paying for it.
W
Wai Ha Lee

10.0.0.0

10.255.255.255

172.16.0.0

172.31.255.255

192.168.0.0

192.168.255.255

All these are non-routable.


(As I've commented on the accepted answer) When I tested an XMLHttpRequest in Node.js, connections to 10.0.0.0 and 10.255.255.255 fired an EACCES error rather than timing out. 10.255.255.1, 172.16.0.0, 172.31.255.255, 192.168.0.0, and 192.168.255.255 did timeout, however.
@JamieBirch Can it be that you were within the network 10.0.0.0/8 when you tested? Or that your router was aware of such a network, either because it was directly connected to it or had a policy that forbids routing to it? In all these cases you would get an explicit error an no timeout.
These may not be viable if your codebase blocks them for security reasons because they are private networks, loopback addresses. en.wikipedia.org/wiki/Private_network webopedia.com/TERM/A/APIPA.html
192.168.0.0 gives me ENETUNREACH, not a timeout.
H
Henrik Heimbuerger

You can use the Python REPL to simulate a timeout while receiving data (i.e. after a connection has been established successfully). Nothing but a standard Python installation is needed.

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()

Now it waits for an incoming connection. Connect whatever you want to test to localhost:9000. When you do, Python will accept the connection and accept() will return it. Unless you send any data through the clientsocket, the caller's socket should time out during the next recv().


Doesn't work for me; something's missing. Perhaps s.listen(5) before s.accept()?
@bmaupin That sounds reasonable, I guess I just forgot that. Edited it in now (however with a backlog queue of 0), thanks!
I was able to put the listen and accept parts in a while True: loop, and that seems to make a nice durable timeout-ing destination to hit for testing.
It works, but it gives "read timeout" error, which is not the same as "connection timeout"
It won't timeout unless you set a timeout, and you haven't.
z
zb226

I would like to point everybody's attention to mitmproxy.

With a config (taken from their examples) of 200:b@100:dr you'll get a connection that randomly drops.


Not same as a timeout
I would like to point out that the edit by @zb226 is not really helpful in this case. while it is true that pathod (what I recommended seven years ago) is now part of mitmproxy, this post makes no sense in its current form. I could not find documentation on how a similar thing is achievable with mitmproxy, so I'm leaving this comment for anyone who wonders how that's supposed to work.
@amenthes well, at least it made you aware of that fact :)
s
stoneboy

How about a software solution:

Install SSH server on the application server. Then, use socket tunnel to create a link between your local port and the remote port on the application server. You can use ssh client tools to do so. Have your client application connect to your mapped local port instead. Then, you can break the socket tunnel at will to simulate the connection timeout.


That won't cause a connection timeout, it will cause a reset.
R
RoHS4U

If you want to use an active connection you can also use http://httpbin.org/delay/#, where # is the time you want their server to wait before sending a response. As long as your timeout is shorter than the delay ... should simulate the effect. I've successfully used it with the python requests package.

You may want to modify your request if you're sending anything sensitive - no idea what happens to the data sent to them.


Max 10 seconds though (If you put in a higher number it will respond after 10 seconds)
T
Timothy Moody

There are services available which allow you to artificially create origin timeouts by calling an API where you specify how long the server will take to respond. Server Timeout on macgyver is an example of such a service.

For example if you wanted to test a request that takes 15 seconds to respond you would simply make a post request to the macgyver API.

JSON Payload:

{
    "timeout_length": 15000
}

API Response (After 15 seconds):

{
    "response": "ok"
}

Server Timeout program on macgyver
https://askmacgyver.com/explore/program/server-timeout/3U4s6g6u


M
Marcin Gil

You might install Microsoft Loopback driver that will create a separate interface for you. Then you can connect on it to some service of yours (your own host). Then in Network Connections you can disable/enable such interface...


佚名

Despite it isn't completely clear which one the OP wants to test: there's a difference between attempting a connection to a non-existent host/port and a timeout of an already established connection. I would go with Rob and wait until the connection is working and then pull the cable. Or - for convenience - have a virtual machine working as the test server (with bridged networking) and just deactivating the virtual network interface once the connection is established.


j
jdi

The technique I use frequently to simulate a random connection timeout is to use ssh local port forwarding.

ssh -L 12345:realserver.com:80 localhost

This will forward traffic on localhost:12345 to realserver.com:80 You can loop this around in your own local machine as well, if you want:

ssh -L 12345:localhost:8080 localhost

So you can point your application at your localhost and custom port, and the traffic will get routed to the target host:port. Then you can exit out of this shell (you may also need to ctrl+c the shell after you exit) and it will kill the forwarding which causes your app to see a connection loss.


A connection loss is not a timeout.
@user207421 that depends on the application and what it perceives. If the application has already established a connection and then you stop the tunnel, if the client doesn't receive a proper close then it may keep waiting on a request until a timeout is reached.
R
Rob

There are a couple of tactics I've used in the past to simulate networking issues;

Pull out the network cable Switch off the switch (ideally with the switch that the computer is plugged into still being powered so the machine maintains it's "network connection") between your machine and the "target" machine Run firewall software on the target machine that silently drops received data

One of these ideas might give you some means of artifically generating the scenario you need


M
Matthew Scharley

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.


M
Matt Howells

The easiest thing would be to drop your connection using CurrPorts.

However, in order to unit test your exception handling code, perhaps you should consider abstracting your network connection code, and write a stub, mock or decorator which throws exceptions on demand. You will then be able to test the application error-handling logic without having to actually use the network.


With CurrPorts, I seem to only be able to close the connection (which causes the next recv() to fail immediately), but could not find a way to simulate a timeout (i.e. no more data is transferred, but the connection stays open).
I appreciated this answer for suggesting a unit test that mocks connection exceptions on demand.
B
Brad Bruce

I had issues along the same lines you do. In order to test the software behavior, I just unplugged the network cable at the appropriate time. I had to set a break-point right before I wanted to unplug the cable.

If I were doing it again, I'd put a switch (a normally closed momentary push button one) in a network cable.

If the physical disconnect causes a different behavior, you could connect your computer to a cheap hub and put the switch I mentioned above between your hub and the main network.

-- EDIT -- In many cases you'll need the network connection working until you get to a certain point in your program, THEN you'll want to disconnect using one of the many suggestions offered.


I
Ivan Marjanovic

For me easiest way was adding static route on office router based on destination network. Just route traffic to some unresponsive host (e.g. your computer) and you will get request timeout.

Best thing for me was that static route can be managed over web interface and enabled/disabled easily.


D
Dmitry Khalatov

You can try to connect to one of well-known Web sites on a port that may not be available from outside - 200 for example. Most of firewalls work in DROP mode and it will simulate a timeout for you.


G
GHad

Plug in your network cable into a switch which has no other connection/cables. That should work imho.