【问题标题】:How to bind socket to local address?如何将套接字绑定到本地地址?
【发布时间】:2019-08-26 02:30:54
【问题描述】:

我搜索了很多,但找不到如何将套接字绑定到本地主机地址 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' 中的地址是我通过在服务器程序中打印主机得到的

【问题讨论】:

  • 您的第二个问题已在help center 中得到解答。如果您需要澄清,请在Meta Stack Overflow
  • IP "192.168.1.6" 必须是您运行此程序的计算机中网卡的 IP。不能是其他电脑的IP。
  • 另外,AF_INET6 必须使用 IPv6 地址。对 IPv4 使用 AF_INET
  • 你不会将地址绑定到套接字,而是将套接字绑定到地址。

标签: python sockets networking ip


【解决方案1】:

我认为你应该这样做:

import socket
host = "...."
port = ...
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.connect((host,port))

【讨论】:

    【解决方案2】:

    “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))
    

    【讨论】:

    • 谢谢...我已经使用您的代码成功创建了服务器...您能否给我客户端程序的代码...我试过但我收到错误 socket.gaierror: [Errno 11001] getaddrinfo failed....我可以通过浏览器使用链接 192.168.1.6:1337/index.html 访问它
    • 如果此解决方案对您有效,那么您很可能获取了错误的 IP 地址。您使用的是 Windows 还是 Linux?
    • 您可能会暂时将“打印主机”添加到服务器代码到代码正在检索的地址,并确定您是否正确。
    • 我在创建服务器时使用打印主机...并在客户端使用相同...更多我使用相同的 ip 通过浏览器访问成功...(我在 windows 上)
    • 你确定你在服务器端使用“s.accept()”函数?
    猜你喜欢
    • 1970-01-01
    • 2020-02-20
    • 1970-01-01
    • 1970-01-01
    • 2017-10-17
    • 2012-06-15
    • 1970-01-01
    • 2011-01-28
    • 2011-11-25
    相关资源
    最近更新 更多