HOWTO · Python

How to Fix ConnectionRefusedError: [Errno 111] Connection Refused

In this article, we will learn what is the ConnectionRefusedError, basically this error indicates that the client is unable to connect to the port on the system running the server script.

On this page

ConnectionRefusedError: [Errno 111] Connection refused means a TCP connection attempt reached a destination that refused it, commonly because no service is accepting connections at that address and port. A successful ping only shows that a host may respond to network probes; it does not confirm that a particular TCP service is listening.

Why Python raises ConnectionRefusedError: [Errno 111] Connection refused

The operating system reports a refusal to Python when the requested TCP endpoint rejects the connection. First check whether the server process is running and listening. Then compare the exact address and port used by the client with the server’s listening address and port. A server bound only to 127.0.0.1 accepts connections from its own machine, not from another computer. A firewall can also reject a connection.

This differs from a hostname lookup failure, which occurs before a TCP connection can be attempted. A timeout or routing failure usually means the client did not receive a refusal response. An incorrect address can lead to different outcomes depending on the network; it does not by itself guarantee this error.

Diagnose and fix a refused Python socket connection

Check the server first, then verify the destination address and port on both sides. Confirm the interface where the server listens: use loopback for a same-machine client, or the intended network interface for another host. Binding to 0.0.0.0 listens on all IPv4 interfaces and can expose the service to other machines, so choose the narrowest interface that fits your setup. Review firewall rules if the service is listening at the expected endpoint.

This self-contained example starts a local server in a background thread, connects a client to the same loopback port, and transfers a byte string. The operating system assigns the port, so both sockets use the same endpoint without a separate file or shell command. The client reads until it receives the known response length; if the server closes sooner, it reports that the response was incomplete instead of presenting partial data as a full message.

import socket
import threading

with socket.socket() as server:
    server.bind(("127.0.0.1", 0))
    server.listen()
    port = server.getsockname()[1]

    def serve():
        connection, _ = server.accept()
        with connection:
            connection.recv(1024)
            connection.sendall(b"hello from server")

    worker = threading.Thread(target=serve)
    worker.start()

    with socket.create_connection(("127.0.0.1", port)) as client:
        client.sendall(b"hello from client")
        response_length = len(b"hello from server")
        response = bytearray()
        complete = True
        while len(response) < response_length:
            chunk = client.recv(response_length - len(response))
            if not chunk:
                complete = False
                break
            response.extend(chunk)
        if complete:
            print(response.decode())
        else:
            print("Server closed before the full response arrived")

    worker.join()

For two separate programs, start the server before the client and keep the server process running while it waits in accept(). Set the same port in both programs, and have the client connect to an address reachable from its own machine. Use 127.0.0.1 only when both programs run on the same host; for a remote client, use the server machine’s reachable interface address and configure access deliberately. The example above is a single-process demonstration of the successful exchange; it does not configure a public-facing listener.

If a hostname is the only part that fails, investigate name resolution separately. socket.gethostbyname("example.com") looks up an IPv4 address; it does not start a service or repair a refused connection. Once the hostname resolves, verify that the returned address is the one where the server listens, and that the client uses the server’s port.

Conclusion

ConnectionRefusedError points to a rejected TCP connection. Check that the server is running, listening on the intended interface, and using the same address and port the client targets. Then review firewall rules; treat hostname resolution as a separate diagnostic.