OSPython Error

ConnectionRefusedError

ConnectionRefusedError: [Errno 111] Connection refused

Traceback

terminal
Traceback (most recent call last):
  File "main.py", line 2, in <module>
    urllib.request.urlopen("http://localhost:8080")
ConnectionRefusedError: [Errno 111] Connection refused

What causes this error

The target host actively refused the connection. No process is listening on the specified port, or the server is bound to a different interface.

How to fix it

Verify the server is running on the expected host and port. Check if the port is correct. Ensure the server is binding to the right interface (0.0.0.0 for all interfaces). Use `netstat` or `ss` to check listening ports.

Code that causes this error

Broken
import urllib.request
urllib.request.urlopen("http://localhost:8080")

Fixed code

Fixed
import urllib.request
import urllib.error

try:
    response = urllib.request.urlopen("http://localhost:8080")
except ConnectionRefusedError:
    print("Server is not running on port 8080")
except urllib.error.URLError as e:
    print(f"Connection failed: {e.reason}")

About ConnectionRefusedError

ConnectionRefusedError is raised when a connection attempt is actively rejected by the target machine. This is a subclass of ConnectionError and corresponds to the POSIX errno ECONNREFUSED. It means that the remote host received the TCP SYN packet but there is no process listening on the target port — the OS responded with a TCP RST (reset) packet.

This is different from a timeout (where no response comes at all, possibly due to a firewall dropping packets). The most common causes are trying to connect to a server that is not running, using the wrong port number, or the server binding to a different network interface (e.g., localhost vs 0.0.0.0). In development environments, this often indicates that you need to start the server process first.

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