如何解决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
解决方法
您有一些错误,并且变量名称非常难以理解。
-
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' # <-- IP of my WiFi card on server
server_port = 4005
s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
#s.bind( (server_ip,server_port) ) # assign server to one local network card
s.bind( ('0.0.0.0',server_port) ) # assign server to all local network cards
text = f'{server_ip}:{server_port}'
print(text)
# --- loop ---
for i in range(1,255):
client_ip = f'192.168.1.{i}'
client_port = 4005
print(f'{client_ip}:{client_port}')
s.sendto(text.encode('utf-8'),(client_ip,client_port))
# --- after loop ---
s.close() # only if you will no use this socket any more
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。