如何使用 python 将套接字绑定到 Windows-10 上的多播 UDP 端口?

问题描述 投票:0回答:1

这是一个与Python相关的编程问题,可能根本无法回答。也许没有解决办法。

但设置如下:我在 HP 笔记本电脑上使用 Windows-10,本地网络中的设备向目的地

239.0.0.4
和端口
45004
发送 UDP 包(可以通过wireshark 确认)。该设备连接到名为
Ethernet
的 USB 以太网连接器,具有静态 IP 地址
192.168.200.5
和子网掩码
255.255.255.0

我正在尝试使用以下 python (3.10.11) 代码创建一个套接字,以便从该设备读取软件包(完全相同的 python 代码在同一台笔记本电脑和同一设备上的 Ubuntu 上运行没有任何问题):

import socket

mcast_grp = "239.0.0.3"
port = 45004
adaptor = "192.168.200.5"
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind((mcast_grp, port))  # FAILING LINE
mreq = struct.pack("4s4s", socket.inet_aton(mcast_grp), socket.inet_aton(adaptor))
sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)

但是 python 代码在指示的行上失败并出现错误

    sock.bind((mcast_grp, port))
OSError: [WinError 10049] The requested address is not valid in its context

有什么方法可以重写这个Python代码,以便它也可以在Windows上运行吗?

python websocket windows-10
1个回答
0
投票

要在 Windows-10 上使用 python 从以太网设备捕获数据,可以使用第三方模块

pyshark
。这允许从设备捕获并选择请求的数据包。

这是如何执行此操作的示例代码:

import pyshark
    
def capture_ethernet_traffic(interface, destination_ip):
    capture = pyshark.LiveCapture(interface=interface)
    for packet in capture.sniff_continuously():
        # Select UDP packets directed to a certain IP address
        if "IP" in packet "UDP" in packet and packet.ip.dst == destination_ip:                   
            # Extract the data as bytes
            captured_data = bytearray.fromhex(packet.data.data)
            print(captured_data)

            # process that data as required
            ...

interface = "Ethernet 7"  # Replace with your interface name
destination_ip = "239.0.0.3"
capture_ethernet_traffic(interface, destination_ip)

就像魅力一样......

© www.soinside.com 2019 - 2024. All rights reserved.