ConnectionRefusedError

In Python, ConnectionRefusedError is a built-in exception that occurs when a connection attempt to a remote server is explicitly refused.

This exception typically happens when the server isn’t running, the server’s firewall is blocking the connection, or the server isn’t listening on the specified port.

As a developer, you might encounter this exception when writing networking code that involves connecting to a server.

ConnectionRefusedError Occurs When

  • Connecting to a server that isn’t running
  • Finding that the server’s firewall is blocking the connection
  • Connecting to a server that isn’t listening on the specified port

ConnectionRefusedError Can Be Used When

  • Handling network connections in client-server applications
  • Implementing retry logic when a connection attempt fails
  • Providing user feedback when a connection can’t be established

ConnectionRefusedError Examples

An example of when the exception appears:

Python
>>> import socket
>>> s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
>>> s.connect(("localhost", 9999))
Traceback (most recent call last):
    ...
ConnectionRefusedError: [Errno 61] Connection refused

An example of how to handle the exception:

Python
>>> import socket
>>> try:
...     s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
...     s.connect(("localhost", 9999))
... except ConnectionRefusedError:
...     print("Connection refused.")
...
Connection refused.

You generally won’t raise ConnectionRefusedError manually in your code. Instead, you handle it when it occurs naturally as part of socket operations.

Tutorial

Socket Programming in Python (Guide)

In this in-depth tutorial, you'll learn how to build a socket server and client with Python. By the end of this tutorial, you'll understand how to use the main functions and methods in Python's socket module to write your own networked client-server applications.

advanced python web-dev

For additional information on related topics, take a look at the following resources:


By Leodanis Pozo Ramos • Updated May 20, 2025