ConnectionError
Error message
ConnectionError: [Errno 111] Connection refused
Quick summary
A network connection could not be established or was lost — the server may be down or unreachable.
Why this happens
Server is not running or is down
Wrong host or port number
Network firewall blocking the connection
Connection was reset by the remote host
Minimal example
import socket
s = socket.socket()
s.connect(('localhost', 9999)) # ConnectionError if nothing is listeningimport socket
try:
s = socket.socket()
s.connect(('localhost', 9999))
except ConnectionError as e:
print(f"Connection failed: {e}")
s = NoneWrap the connection in try/except ConnectionError to handle servers that are down or unreachable.
How to diagnose
Verify the server is running and the port is correct
Check network connectivity (ping the host)
Look for firewall rules blocking the connection
How to fix
Start the server or use the correct host/port
Implement retry logic with exponential backoff
Use try/except ConnectionError to handle failures
Check firewall and network configuration
How to prevent
Implement connection retry logic
Use connection pooling with timeouts
Validate host and port before connecting
Related Resources
Related Lessons
- Exceptions
Network errors.