socket.error
PythonERRORNotableNetwork

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.

What this means

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.

Why it happens
  1. 1Connection refused — no service listening on the target port
  2. 2Broken pipe — remote end closed the connection while writing
  3. 3Network unreachable — no route to host

Fix

Inspect errno for specific handling

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:
        raise

Why this works

errno constants are platform-stable identifiers for POSIX error codes; they are more reliable than matching on error message strings.

Code examples
Trigger connection refusedpython
import socket
s = socket.socket()
s.connect(('127.0.0.1', 1))  # ConnectionRefusedError (socket.error)
Version notes
Python 3.3

socket.error became an alias for OSError. ConnectionRefusedError, ConnectionResetError etc. are specific OSError subclasses.

Sources
Official documentation ↗

Python Docs — socket module

Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev

← All Python errors