python - 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
推荐阅读
- python - 在 pandas 中,如何识别具有共同值的记录并替换其中一个值以匹配另一个?
- python - 使用 scanpy 运行 paga 时出现 ModuleNotFoundError
- excel - .bat 文件在后台运行 excel 宏(或 .vbs 解决方案)
- pyspark - 使用 pyspark 将 unix_timestamp 转换为 utc_timestamp,unix_timestamp 不起作用
- ruby-on-rails - Ruby 可枚举块变量赋值
- javascript - 保持文件打开以进行读/写的最佳方法是什么?
- wordpress - ACF 自定义字段未显示在自定义分类模板上
- azure - 使用表格模型的 Power BI 中的行级别安全错误
- git - 如何将所有分支的存储库从 Bitbucket 复制到 CodeCommit 但没有历史记录?
- api - 应该在哪里验证用户输入:GUI 和/或 API?