Socket-level network error (alias for OSError)
Quick Answer
Catch OSError (or socket.error) and inspect err.errno against errno constants to distinguish connection refused (ECONNREFUSED) from timeout (ETIMEDOUT).
Production Risk
Medium.
socket.error is an alias for OSError in Python 3.3+ — it covers all OS-level socket failures including connection refused, broken pipe, and host unreachable. The errno attribute identifies the specific POSIX error.
- 1Connection refused — no service listening on the target port
- 2Broken pipe — remote end closed the connection while writing
- 3Network unreachable — no route to host
Fix
Inspect errno for specific handling
import socket
import errno
try:
sock = socket.create_connection(('example.com', 80), timeout=5)
except socket.timeout:
print('Connection timed out')
except OSError as e:
if e.errno == errno.ECONNREFUSED:
print('Connection refused — is the server running?')
elif e.errno == errno.ENETUNREACH:
print('Network unreachable')
else:
raiseWhy this works
errno constants are platform-stable identifiers for POSIX error codes; they are more reliable than matching on error message strings.
import socket
s = socket.socket()
s.connect(('127.0.0.1', 1)) # ConnectionRefusedError (socket.error)socket.error became an alias for OSError. ConnectionRefusedError, ConnectionResetError etc. are specific OSError subclasses.
Python Docs — socket module
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev