How to Fix Socket.Gaierror: [Errno 8] Nodename Nor Servname Provided, or Not Known in Python

Rohan Timalsina Feb 02, 2024
  1. Recreate socket.gaierror: [Errno 8] nodename nor servname provided, or not known in Python
  2. Fix socket.gaierror: [Errno 8] nodename nor servname provided, or not known in Python
How to Fix Socket.Gaierror: [Errno 8] Nodename Nor Servname Provided, or Not Known in Python

The socket module in Python offers an interface to the Berkeley sockets API. Sockets help connect two nodes on a network so they can communicate with each other.

Sometimes, you might get a socket error in Python when working with socket modules. This tutorial will teach you to solve that error in Python.

Recreate socket.gaierror: [Errno 8] nodename nor servname provided, or not known in Python

Here, we will recreate the socket.gaierror and explain how to solve it in Python.

The following script is a server that waits for a client to connect to the specified port.

import socket

s = socket.socket()
host = "localhost"
port = 1234
s.bind((host, port))

s.listen(5)
while True:
    c, addr = s.accept()
    print("Connection received from", addr)
    c.send("Thank you for connecting")
    c.close()

The socket.socket() function creates a socket object and the socket.bind() binds the socket to the specified address.

The socket.accept() accepts the connection when a client connects. When the connection is successful, it returns the output and closes the connection.

Below is a client that connects to the specified host.

import socket

s = socket.socket()
host = socket.gethostname()
port = 1234

s.connect((host, port))
print(s.recv(1024))
s.close

Now run the server.py in the background and run client.py next.

python server.py &
python client.py

Output:

socket error

Fix socket.gaierror: [Errno 8] nodename nor servname provided, or not known in Python

The output shows that the error occurred in line 7, where the code reads s.connect((host, port)). This is because the socket.gethostname() returns the machine’s hostname where the Python interpreter is currently running.

But you have to specify the host IP address instead of the hostname. You can solve this issue by assigning the host as localhost or 127.0.0.1 in the client.py file.

import socket

s = socket.socket()
host = "localhost"
port = 1234

s.connect((host, port))
print(s.recv(1024))
s.close

Output:

socket error fixed - connection successful

Now we know how to fix the socket error in Python. We hope you find this tutorial helpful.

Rohan Timalsina avatar Rohan Timalsina avatar

Rohan is a learner, problem solver, and web developer. He loves to write and share his understanding.

LinkedIn Website

Related Article - Python Error