使用套接字发送消息时指定网络

时间:2019-02-02 17:52:31

标签: python networking minecraft

当前连接到2个独立的网络,一个以太网和一个无线网络。如何指定sendto()发送到哪个网络?

当前使用有问题的以下基本代码:

BROADCAST_IP = "224.0.2.60"
BROADCAST_PORT = 4445
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
msg = "Testing"
sock.sendto(msg, (BROADCAST_IP, BROADCAST_PORT))

当我运行该示例时,它似乎仅通过以太网连接使用IP,而不是无线连接。

简而言之,代码使用专用的多播地址通过服务器打补丁。

完整代码在这里

import socket
import time

servers = [
    ["Testing a server  :) [Test broadcast]", 25565]
    ]

BROADCAST_IP = "224.0.2.60"
BROADCAST_PORT = 4445

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)

print "Broadcasting to specified port"

while 1:
    for server in servers:
        print("Broadcasting ", len(servers), " connections")
        msg = "[MOTD]%s[/MOTD][AD]%d[/AD]" % (server[0], server[1])
        sock.sendto(msg, (BROADCAST_IP, BROADCAST_PORT))
    time.sleep(1)

0 个答案:

没有答案