[英]I get this error:' socket.gaierror: [Errno 11001] getaddrinfo failed' when I use the socket module in python
So I am making a simple script which just sends messages from a client to the server.所以我正在制作一个简单的脚本,它只是将消息从客户端发送到服务器。 When the client and the server is on the same computer, the script runs perfectly but when I use another laptop and try to send a message to the server it shows this error on the client laptop.
当客户端和服务器在同一台计算机上时,脚本运行完美,但是当我使用另一台笔记本电脑并尝试向服务器发送消息时,它会在客户端笔记本电脑上显示此错误。
server script:服务器脚本:
import threading
HEADER = 64
PORT = 5000
SERVER = '######'
ADDR = ('', PORT)
FORMAT = 'utf-8'
DISCONNECT_MSG = '//*DISCONNECT*//'
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server.bind(ADDR)
def handle_client(conn, addr):
print(f'[NEW CONNECTION] {addr}')
connected = True
while connected:
msg_len = conn.recv(HEADER).decode(FORMAT)
if msg_len:
msg_len = int(msg_len)
msg = conn.recv(msg_len).decode(FORMAT)
if msg == DISCONNECT_MSG:
connected = False
print(f'[{addr}] {msg}')
conn.close()
def start():
print(f'[LISTENING] listening on {SERVER}')
server.listen()
while True:
conn, addr = server.accept()
# hc for hand client
thread_hc = threading.Thread(target=handle_client, args=(conn, addr))
thread_hc.start()
print(f'[ACTIVE CONNECTIONS] {threading.activeCount() - 1}')
print('[STARTING] server is starting.....')
start()
client script:客户端脚本:
HEADER = 64
PORT = 5000
FORMAT = 'utf-8'
DISCONNECT_MSG = '//*DISCONNECT*//'
SERVER = '######'
ADDR = (SERVER, PORT)
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(ADDR)
def send(msg):
message = msg.encode(FORMAT)
msg_length = len(message)
send_length = str(msg_length).encode(FORMAT)
send_length += b' ' * (HEADER - len(send_length))
client.send(send_length)
client.send(message)
try:
while True:
msg = input('message: ')
send(msg)
if msg == DISCONNECT_MSG:
break
except BrokenPipeError:
print('the connection was broken')
Can you tell me what is the problem in the code.你能告诉我代码中有什么问题吗? I am new to sockets in python, so if I am making any rookie mistakes, please overlook it.
我是python中sockets的新手,所以如果我犯了任何菜鸟错误,请忽略它。
getaddrinfo failed
is an error that means the OS couldn't resolve an IP address for a DNS name. getaddrinfo failed
是一个错误,表示操作系统无法解析 DNS 名称的 IP 地址。
For example, if SERVER
is a-name-with-no-ip.example.com and you try to connect to it, it will throw a getaddrinfo failed
.例如,如果
SERVER
是 a-name-with-no-ip.example.com 并且您尝试连接到它,它将抛出getaddrinfo failed
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.