亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Python - 使用套接字將數據發送到網絡上的每個 IP 地址

Python - 使用套接字將數據發送到網絡上的每個 IP 地址

繁花不似錦 2023-06-20 13:48:06
我正在尋找的是我的 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 sockethost = socket.gethostbyname(socket.gethostname())listeningPort = 4005s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)i = 1while 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
查看完整描述

1 回答

?
慕田峪4524236

TA貢獻1875條經驗 獲得超5個贊

你有一些錯誤和非常難以理解的變量名稱。

  • 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


查看完整回答
反對 回復 2023-06-20
  • 1 回答
  • 0 關注
  • 175 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號