Connection Refused vs. Timeout: Diagnosing Linux TCP Failures via Network Namespaces
Reproduce and isolate network connection errors in isolated Linux network namespaces with iptables, ss, and tcpdump.
Key Takeaways & Prerequisites
- Connection Refused indicates the target IP is reachable, but the destination port has no listening process or the SYN packet was rejected by an iptables/nftables REJECT rule.
- Connection Timeout occurs when packets are silently dropped along the network path by security groups, firewalls (DROP target), or dead routing gateways.
- Linux Network Namespaces (netns) allow creating isolated networking stacks on a single host to safely reproduce packet drops and latency issues.
- Use tcpdump, ip route, and ss -tulpn systematically to isolate whether a failure is caused by routing, listening sockets, or packet filtering.
Architecture & Execution Flow
- 01 →Refused vs TimeoutRST packet vs silent packet drop
- 02 →Netns IsolationSimulate virtual network topologies
- 03 →Packet Tracingtcpdump and conntrack inspection
- 04 →Resolution MatrixFix routing, firewall, or socket
Table of Contents
When an inter-service call fails, logs often reduce the incident to a single line: connection refused or timed out. Engineers frequently treat these two errors as interchangeable: bounce the service, expose another port, and retry. In reality, these messages point to fundamentally different failure domains. Understanding the difference tells you whether to inspect ss, routing tables, or firewall rules first—eliminating guesswork.
This guide walks through building an isolated sandbox to reproduce each failure mode deterministically, analyze its telemetry and signatures, and synthesize a production-grade diagnostic runbook.
Scope: The lab runs entirely as an unprivileged user inside an ephemeral network namespace—no sudo required, zero mutations to host firewall rules or interfaces, and no cloud dependencies. All commands were verified on Ubuntu 22.04 (Linux kernel 5.15, iproute2 5.15, nftables 1.0.2, curl 7.81, Python 3.10). The AWS security group discussion at the end is derived from architectural documentation, not live benchmarks on AWS.
1. Three Failure Classes and Their OSI/Network Layers
An HTTP request traverses multiple stages: name resolution, routing, the TCP handshake, and finally application-layer processing. A failure at any stage surfaces distinct telemetry. The curl manual defines standard exit codes [1]; three are critical to memorize:
- 6 – Couldn't resolve host: DNS resolution failure or misconfigured
/etc/hosts. No TCP packets were ever dispatched. - 7 – Failed to connect to host: An immediate, explicit negative response: the target machine returned a TCP RST because no process is listening on the port, a middlebox/firewall actively rejected the packet, or the local kernel lacks a route to the destination.
- 28 – Operation timeout: The initial SYN packet egressed, but no response was received before the deadline expired. Typically caused by silent packet drops (blackholing) in firewalls, a non-existent target IP, or asymmetric/blocked return routing paths.
Key takeaway: Exit code 7 fails almost instantaneously, whereas exit code 28 consistently blocks for the full configured timeout duration. Measuring time-to-failure alone eliminates half of the potential root causes.
2. Lab Environment Setup
You will need a Linux environment with unshare (util-linux), ip (iproute2), nft, curl, and Python 3. Verify that your kernel allows unprivileged user namespaces:
command -v unshare ip nft curl python3
unshare --net --map-root-user true && echo "userns OK"
If the second command fails with Operation not permitted, your distribution restricts unprivileged user namespaces (Ubuntu 23.10+ enforces this via AppArmor profiles). In that case, run the lab inside a disposable VM rather than weakening host security policies.
Create the lab workspace and a static payload:
export LAB="$HOME/net-lab"
mkdir -p "$LAB/www"
echo "hello from lab" > "$LAB/www/index.html"
Spawn a shell inside an isolated network namespace. The --map-root-user flag maps your UID to root inside the namespace, granting capability permissions to manage network interfaces and nftables rules without affecting host network configuration [2]:
unshare --net --map-root-user bash
From this point forward, execute all commands within this isolated subshell. Initially, the namespace contains only a down lo interface. Bring it up and provision a dummy interface lab0 configured with 10.99.0.10/24 to simulate a local server IP:
cd "$LAB"
ip link set lo up
ip link add lab0 type dummy
ip addr add 10.99.0.10/24 dev lab0
ip link set lab0 up
ip -br addr
3. Failure Classification Script
Rather than manually parsing raw errors, use this probe script. It wraps curl with a 3-second connect timeout and maps exit codes to actionable root-cause candidates. Save it as $LAB/probe.sh:
#!/usr/bin/env bash
# probe.sh HOST PORT [PATH] - Classify connection errors based on curl exit codes
set -u
host="${1:?host}"; port="${2:?port}"; path="${3:-/}"
out=$(curl -sS -o /dev/null --connect-timeout 3 -m 5 \
-w '%{http_code} connect=%{time_connect}s total=%{time_total}s' \
"http://${host}:${port}${path}" 2>&1)
rc=$?
case "$rc" in
0) verdict="OK: TCP and HTTP both responded" ;;
6) verdict="DNS: Failed to resolve hostname" ;;
7) verdict="REFUSED/NO ROUTE: Inspect ss -ltn, bind address, ip route, reject rules" ;;
28) verdict="TIMEOUT: Packet dropped; inspect firewall drop rules/security groups" ;;
52) verdict="EMPTY: TCP connected, but server closed connection without response" ;;
56) verdict="RESET: Connection terminated prematurely" ;;
*) verdict="OTHER: Check exit code $rc in man curl" ;;
esac
printf '%-18s rc=%-3s %s\n %s\n' "${host}:${port}" "$rc" "$verdict" "$out"
exit "$rc"
chmod +x "$LAB/probe.sh"
Codes 52 and 56 are not triggered in this lab but are retained because they frequently occur when reverse proxies or load balancers abruptly sever connections.
4. Scenario A: Service Bound Exclusively to 127.0.0.1
This is a quintessential misconfiguration following environment promotions or transitioning apps from local dev to production. Launch the Python web server bound strictly to the loopback address [3]:
python3 -m http.server 8080 --bind 127.0.0.1 --directory "$LAB/www" >/dev/null 2>&1 &
APP_PID=$!
sleep 1
./probe.sh 127.0.0.1 8080
./probe.sh 10.99.0.10 8080
ss -ltnp 'sport = :8080'
The first probe returns rc=0 with HTTP 200. The second returns rc=7 immediately. Inspecting ss reveals the Local Address is 127.0.0.1:8080: the socket only accepts connections targeting loopback. SYN packets destined for 10.99.0.10 find no listening socket; the kernel immediately responds with a TCP RST, causing curl to report Connection refused. In ss, -l filters for listening sockets and -p identifies the owning process [4].
Remediate this by binding to the specific external interface, or 0.0.0.0 to listen on all interfaces:
kill "$APP_PID"; sleep 0.5
python3 -m http.server 8080 --bind 0.0.0.0 --directory "$LAB/www" >/dev/null 2>&1 &
APP_PID=$!
sleep 1
./probe.sh 10.99.0.10 8080
This invocation yields rc=0. In production, binding to 0.0.0.0 requires network-level or host-level firewall controls to restrict unauthorized ingress; avoid changing bind addresses as an unvetted quick fix.
5. Scenario B: Firewall Drop vs. Firewall Reject
With the service running, inject an nftables rule to block port 8080 on lab0 using a silent drop policy:
nft add table inet lab
nft add chain inet lab input '{ type filter hook input priority 0; policy accept; }'
nft add rule inet lab input ip daddr 10.99.0.10 tcp dport 8080 counter drop
./probe.sh 10.99.0.10 8080
nft list chain inet lab input
The probe blocks for the full 3-second timeout and exits with rc=28. The destination host emits no error frames; the SYN packet is simply discarded. The only breadcrumb is the rule's packet counter incrementing (counter packets N). A counter that ticks up synchronously with your connection attempts is definitive proof of an active firewall drop rule.
Now mutate the rule to a reject policy to observe the difference [5]:
nft flush chain inet lab input
nft add rule inet lab input ip daddr 10.99.0.10 tcp dport 8080 counter reject with tcp reset
./probe.sh 10.99.0.10 8080
ss -ltn 'sport = :8080'
Now the probe returns rc=7 instantaneously, even though ss confirms the process is actively listening. This is a critical debugging pitfall: connection refused does not strictly mean the service is down. If ss shows the socket in LISTEN on the destination, but the client observes a connection refusal, inspect upstream packet filters for active reject rules.
Tear down the table and confirm baseline connectivity is restored:
nft delete table inet lab
./probe.sh 10.99.0.10 8080
6. Scenario C: Missing Routes vs. Unreachable Hosts
Attempt to connect to an IP address outside any known subnet in the namespace's Forwarding Information Base (FIB):
ip route
ip route get 10.99.1.5
./probe.sh 10.99.1.5 8080
ip route contains only 10.99.0.0/24 dev lab0. Consequently, ip route get 10.99.1.5 returns Network is unreachable, and the probe fails immediately with rc=7. The root cause is strictly client-side: a missing default gateway or routing entry to the target CIDR block [6]. The fix belongs on the calling host, not the destination server.
Next, test an IP that falls within the local subnet, but has no active host attached:
ip route get 10.99.0.77
./probe.sh 10.99.0.77 8080
The kernel has a valid route (dev lab0) and transmits the SYN packet. Because the dummy interface has no peer listening to respond, the probe hangs and exits with rc=28. On a physical or virtual Ethernet segment, failing ARP/NDP resolution typically yields No route to host after an initial delay, which curl also categorizes under exit code 7. In both scenarios, verify host availability and IP addressing accuracy.
7. Scenario D: DNS Resolution Failures
The .invalid top-level domain is reserved by RFC 6761 to guarantee that DNS resolution deterministically fails [7]:
getent hosts api.lab.invalid; echo "getent rc=$?"
./probe.sh api.lab.invalid 8080
getent returns exit code 2 (not found) and the probe immediately yields rc=6. In this sandboxed namespace with no external connectivity, any hostname not mapped in /etc/hosts will fail. In production, .invalid triggers an NXDOMAIN response from upstream resolvers. Because zero TCP packets are dispatched, inspecting ss or firewall logs on the destination is useless. Always validate with getent hosts <hostname> first: it leverages the Name Service Switch (NSS) pipeline (/etc/hosts, systemd-resolved, DNS) used by the application runtime, providing a more accurate assessment than querying resolvers directly via dig.
8. Production Triage Runbook
Synthesizing these failure patterns yields a standardized, deterministic triage workflow for connection failures:
- Execute the probe from the originating host or container context. Record the precise exit code and latency/time-to-failure.
- Exit Code 6 (DNS Failure): Run
getent hosts <hostname>, audit/etc/resolv.conf, and verify external/internal DNS records. Halt further network debugging until name resolution is functional. - Exit Code 7 (Immediate Failure): On the destination host, run
ss -ltnpto confirm the target port is inLISTENstate and bound to the expected interface/IP. If it is listening correctly, inspect packet filters for explicit reject rules (nft list rulesetoriptables -S). On the source host, executeip route get <ip>to eliminate routing blackholes or missing routes. - Exit Code 28 (Timeout / Hang): Check destination host firewall drop counters while re-triggering the connection. Trace upstream middleboxes, network ACLs, and cloud security groups. Confirm target host health and reachability.
- Exit Code 0 with HTTP 5xx: The transport and network layers are healthy; escalate to application runtimes, downstream dependencies, or reverse proxy logs.
In AWS VPC, Security Groups are stateful and implement allow-only logic (no explicit deny rules); return traffic is automatically permitted for established inbound flows [8]. Consequently, missing inbound Security Group rules manifest as silent packet drops (Exit Code 28), never as explicit connection refusals. If you see an immediate connection refused from an EC2 instance, packets are successfully reaching the operating system—meaning the issue is either an unbound socket, an inactive daemon, or a local OS-level reject rule.
9. Common Lab Troubleshooting
unshare: write failed /proc/self/uid_maporOperation not permitted: Unprivileged user namespaces are disabled at the kernel or LSM level. Use a standalone VM; do not globally disable host security controls.nft: Operation not permitted: Thenftcommand was executed outside the unshared network namespace. Exit and re-enter using the command in Step 2. Do not escalate withsudo, which would inject rules into the host's actual firewall tables.Address already in use: An orphaned server process is occupying the port. Terminate it viakill "$APP_PID"or isolate the PID usingss -ltnp 'sport = :8080'.- Probe returns
rc=7in Scenario A despite binding to0.0.0.0: The Python interpreter has not finished binding to the socket; increase thesleepduration.
10. Teardown and Cleanup
All virtual interfaces, routes, and nftables rules are scoped strictly to the ephemeral namespace. Terminating the background server and exiting the subshell automatically purges all network state:
kill "$APP_PID" 2>/dev/null
exit
Once back in the parent shell, remove the lab artifacts:
rm -rf "$HOME/net-lab"
This sandbox installs no system packages, mutates no /etc configurations, and provisions no cloud infrastructure—incurring zero infrastructure overhead.
Conclusion
connection refused and timed out represent two fundamentally distinct failure modes. A refusal is an active, explicit rejection: inspect listening sockets, bind configurations, and reject rules. A timeout is dead silence: investigate silent packet drops, security groups, and unreachable hosts. Leveraging curl exit codes alongside ss -ltnp, ip route get, and nft list ruleset allows SREs to isolate the vast majority of transport-layer incidents before touching application code. If your workload runs on Docker Compose, see Docker Compose with Healthchecks and Volumes for container network diagnostics; for zero-trust remote access without opening public ports, consult Tailscale Serve.
References
Verified as of October 24, 2026:
[1] https://curl.se/docs/manpage.html — curl(1), EXIT CODES (6, 7, 28, 52, 56) and --connect-timeout
[2] https://man7.org/linux/man-pages/man1/unshare.1.html — unshare(1), --net, --map-root-user
[3] https://docs.python.org/3/library/http.server.html — Python http.server, --bind, --directory
[4] https://man7.org/linux/man-pages/man8/ss.8.html — ss(8), -l, -t, -n, -p, and port filtering
[5] https://wiki.nftables.org/wiki-nftables/index.php/Rejecting_traffic — nftables, reject with tcp reset
[6] https://man7.org/linux/man-pages/man8/ip-route.8.html — ip-route(8), ip route get
[7] https://www.rfc-editor.org/rfc/rfc6761 — RFC 6761, Special-Use Domain Name .invalid
[8] https://docs.aws.amazon.com/vpc/latest/userguide/security-group-rules.html — AWS VPC, Security group rule characteristics