我进行了很多搜索,但是找不到如何将套接字绑定到本地主机地址192.168.1.6。
我尝试过
host = "192.168.1.6"
port = 1337
s.bind((host,port))
但是它给出了错误
socket.gaierror: [Errno 11001] getaddrinfo failed
这是我的完整代码:
编辑:- 服务器
import socket
def 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 = 1337
s = 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 = 1337
print(host)
print(host_name)
s = socket(AF_INET, SOCK_STREAM)
s.connect((host_name, port))
第3行“ 192.168.1.6”中的地址是我通过在服务器程序中打印主机得到的地址
答案 0 :(得分:0)
我认为您应该这样做:
import socket
host = "...."
port = ...
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((host,port))
答案 1 :(得分:-1)
“ getaddrinfo失败”错误可能意味着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))