ConnectionError
ConnectionError: [Errno 111] Connection refused
Traceback
Traceback (most recent call last):
File "main.py", line 3, in <module>
s.connect(("localhost", 9999)) # nothing listening
ConnectionError: [Errno 111] Connection refusedWhat causes this error
A network connection could not be established, was refused by the remote host, was reset during communication, or was broken. The remote server may be down, a firewall may be blocking traffic, or the network is unreachable.
How to fix it
Implement retry logic with exponential backoff. Check that the server is running and accessible. Verify firewall rules and network connectivity. Use connection timeout parameters to fail fast.
Code that causes this error
import socket
s = socket.socket()
s.connect(("localhost", 9999)) # nothing listeningFixed code
import socket
import time
for attempt in range(3):
try:
s = socket.socket()
s.settimeout(5)
s.connect(("localhost", 9999))
break
except ConnectionError:
print(f"Attempt {attempt + 1} failed, retrying...")
time.sleep(2 ** attempt)About ConnectionError
ConnectionError is the base class for network connection errors. It is a subclass of OSError and has specific subclasses: ConnectionRefusedError (remote host actively refused), ConnectionResetError (connection reset by peer), ConnectionAbortedError (connection aborted by local host), and BrokenPipeError (writing to a closed pipe/socket). These errors arise in socket programming, HTTP requests, database connections, and any network I/O.
ConnectionError is commonly seen when a server is not running, a firewall blocks the connection, a network is unreachable, or a connection times out at the TCP level. Retry logic with exponential backoff is the standard pattern for handling transient connection failures. Libraries like `requests` wrap these into their own exception hierarchy, and `urllib3` provides configurable retry policies.
Common scenarios
Running scripts without sufficient file system permissions
Connecting to servers that are not running or are unreachable
Installing Python packages without proper environment setup
Running out of disk space or file descriptors during I/O operations