How to Fix Socket.Gaierror: [Errno 8] Nodename Nor Servname Provided, or Not Known in Python
-
Recreate
socket.gaierror: [Errno 8] nodename nor servname provided, or not known
in Python -
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:
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:
Now we know how to fix the socket error
in Python. We hope you find this tutorial helpful.
Related Article - Python Error
- Can Only Concatenate List (Not Int) to List in Python
- How to Fix Value Error Need More Than One Value to Unpack in Python
- How to Fix ValueError Arrays Must All Be the Same Length in Python
- Invalid Syntax in Python
- How to Fix the TypeError: Object of Type 'Int64' Is Not JSON Serializable
- How to Fix the TypeError: 'float' Object Cannot Be Interpreted as an Integer in Python