Python - 使用套接字将数据发送到网络上的每个 IP 地址

我正在寻找的是我的 python 服务器,它只是一个响应客户端输入的专用服务器,当它开始将它的 IP 地址发送到端口 4005 上网络上的每个 IP 时。我不知道如何计算确切地找出哪些 IP 可以有效地发送到网络上。


这是我认为可行的代码,但引发了异常:


File "E:\Python\server client comms\messageEveryIP.py", line 11, in <module>

    s.bind((curIP, listeningPort))

OSError: [WinError 10049] The requested address is not valid in its context

在我的例子中,它在 192.168.1.2 上出错,因为该 IP 上没有机器。


import socket

host = socket.gethostbyname(socket.gethostname())

listeningPort = 4005


s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)


i = 1

while i < 255:

    curIP = '192.168.1.' + str(i)

    listeningAddress = (curIP, listeningPort)

    s.bind((curIP, listeningPort))

    s.sendto(host.encode('utf-8'), listeningAddress)

    s.close()

    i += 1


繁花不似锦
浏览 149回答 1
1回答

慕田峪4524236

你有一些错误和非常难以理解的变量名称。bind()用于将服务器分配给本地网卡 - 而不是客户端 IP - 并且只使用一次 - 在循环之前不要关闭套接字,因为(我记得)它需要再次创建套接字import socket#server_ip = socket.gethostbyname(socket.gethostname()) # this gives me `127.0.1.1` because I have it in `/etc/hosts`server_ip = '192.168.1.13'&nbsp; # <-- IP of my WiFi card on serverserver_port = 4005s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)#s.bind( (server_ip, server_port) ) # assign server to one local network cards.bind( ('0.0.0.0', server_port) )&nbsp; # assign server to all local network cardstext = f'{server_ip}:{server_port}'print(text)# --- loop ---for i in range(1, 255):&nbsp; &nbsp; client_ip = f'192.168.1.{i}'&nbsp; &nbsp; client_port = 4005&nbsp; &nbsp; print(f'{client_ip}:{client_port}')&nbsp; &nbsp; s.sendto(text.encode('utf-8'), (client_ip, client_port))# --- after loop ---s.close()&nbsp; # only if you will no use this socket any more
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python