OSPython Error

ConnectionError

ConnectionError: [Errno 111] Connection refused

Traceback

terminal
Traceback (most recent call last):
  File "main.py", line 3, in <module>
    s.connect(("localhost", 9999))  # nothing listening
ConnectionError: [Errno 111] Connection refused

What 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

Broken
import socket
s = socket.socket()
s.connect(("localhost", 9999))  # nothing listening

Fixed code

Fixed
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

1

Running scripts without sufficient file system permissions

2

Connecting to servers that are not running or are unreachable

3

Installing Python packages without proper environment setup

4

Running out of disk space or file descriptors during I/O operations

Related errors