我搜索了很多,但找不到如何将套接字绑定到本地主机地址 192.168.1.6。我试过host = "192.168.1.6"port = 1337s.bind((host,port))但它给出了错误socket.gaierror: [Errno 11001] getaddrinfo failed这是我的完整代码:编辑:- 服务器import socketdef function(c): c.send('HTTP/1.0 200 OK\n'.encode()) c.send('Content-Type: text/html\n'.encode()) c.send("""<html> <body> <h1> Hello World </h1> this is my server! </body> </html>""".encode())with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.connect(("122.168.223.131", 80)) host = s.getsockname()[0] print(host)port = 1337s = socket.socket()s.bind((host, port))s.listen(1)c, (client_host, client_port) = s.accept()c.recv(1000)print('Got connection from', client_host, client_port)function(c)客户 :-from socket import *host = gethostbyaddr('192.168.1.6')print()host_name = host[0]port = 1337print(host)print(host_name)s = socket(AF_INET, SOCK_STREAM)s.connect((host_name, port))第 3 行“192.168.1.6”中的地址是我通过在服务器程序中打印主机得到的
2 回答
呼唤远方
TA贡献1856条经验 获得超11个赞
我认为你应该这样做:
import socket
host = "...."
port = ...
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((host,port))
米脂
TA贡献1836条经验 获得超3个赞
“getaddrinfo failed”错误可能意味着 IP 地址可能不是本地网络上您计算机的地址。试试这个
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect(("8.8.8.8", 80))
host = s.getsockname()[0]
port = 1337
s = socket.socket()
s.bind((host, port))
添加回答
举报
0/150
提交
取消
