简体   繁体   中英

Server and client issue: socket.gaierror: [Erno 11001] getaddrinfo failed

I'm new to how networking works and I'm trying to write two scripts for a class assignment, one acts as a server and one as a client. Both the server and client scripts are to be run on the same computer and each one uses two different ports (client port and server port). The client should be able to send a message to the server and then get a message back if the send was successful. This is the client code:

from socket import *
serverName = 'hostname'
serverPort = 2000
clientSocket = socket(AF_INET, SOCK_DGRAM)
message = input('Input lowercase sentence:')
clientSocket.sendto(message.encode(), (serverName, serverPort))
modifiedMessage, serverAddress = clientSocket.recvfrom(3000)
print(modifiedMessage.decode())
clientSocket.close()

And this is the server code:

from socket import *
serverPort = 2000
serverSocket = socket(AF_INET, SOCK_DGRAM)
serverSocket.bind(('', serverPort))
print("The server is ready to receive")
while True:
   message, clientAddress = serverSocket.recvfrom(3000)
   modifiedMessage = message.decode().upper()
   serverSocket.sendto(modifiedMessage.encode(), clientAddress)

The server code runs fine but I get this error from running the client code:

socket.gaierror: [Erno 11001] getaddrinfo failed

Specifically, it doesn't like

clientSocket.sendto(message.encode(), (serverName, serverPort)

I saw multiple threads on here about this error but none of them really helped with my issue. I already checked to ensure both the ports are definitely open before executing both scripts, and they are. My initial guess is that it can't find the actual server port, even though it's up and running and waiting for a response. So I'm stumped. What does this error mean and how can I resolve this?

You forgot to actually connect the client socket to the server socket before trying to send a message:

from socket import *
serverName = 'localhost'
serverPort = 2000
clientSocket = socket(AF_INET, SOCK_DGRAM)
clientSocket.connect((serverName, serverPort))
message = input('Input lowercase sentence:')
clientSocket.sendto(message.encode(), (serverName, serverPort))
modifiedMessage, serverAddress = clientSocket.recvfrom(3000)
print(modifiedMessage.decode())
clientSocket.close()

I also changed the serverName to localhost .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM