Lingua-e
Python

What is a ConnectionRefusedError?

← Errors

ConnectionRefusedError is raised when a TCP connection attempt is actively rejected by the target host. This means the host is reachable but no process is listening on the specified port. It is a subclass of ConnectionError and OSError.

Why it happens

  • The target service (database, web server, etc.) is not running.
  • The service is running but on a different port than specified.
  • A firewall is blocking the connection and sending a TCP RST packet.
  • The server process crashed or has not finished starting up yet.

Examples

Python

Code that triggers the error

import socket

s = socket.create_connection(("localhost", 9999))

Error output

ConnectionRefusedError: [Errno 111] Connection refused

How to fix it

Verify the target service is running and listening on the expected port. Implement retry logic with exponential backoff for services that may not be ready immediately. Check firewall rules and ensure the port number in your configuration matches the server.

Fixed code

import socket

try:
    s = socket.create_connection(("localhost", 9999))
except ConnectionRefusedError:
    print("Server is not running on port 9999")

Related errors

Ready to practice your English at work?

Lingua-e has interactive exercises built around real developer conversations: standups, code reviews, retrospectives, and more. Practice until it comes naturally.

Try Lingua-e for free