首页 > 解决方案 > 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

标签: pythonsockets

解决方案


您有一些错误和非常难以理解的变量名称。

  • 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

推荐阅读