如何使用 psutil 与 python 建立实时 UDP 连接

How can I get live established UDP connections with python using psutil

我正在尝试获取连接到使用 UDP 协议的计算机的目标 IP(远程主机)地址,但我使用 psutil

得到的结果为空

我写的剧本

import psutil

def GetServerIP():
    PROCNAME = "theprocessname.exe"
    for proc in psutil.process_iter():
        if proc.name() == PROCNAME:
            pinfo = proc.as_dict(attrs=['pid', 'name', 'create_time'])
            pidnumber = pinfo["pid"]
            print("Process is runnging on number: %r" % (pidnumber))           
    for connection in psutil.net_connections(kind='udp4'):
        if pidnumber in connection:
            print(connection.raddr)

GetServerIP()

该脚本适用于 TCP 连接,但对在我的本地计算机上建立的 UDP 连接不提供任何信息。

我通读了 psutil 文档,但仍然无法弄清楚为什么它在 UDP 上没有返回结果

我可以使用 wireshark 验证是否已建立 UDP 数据包发送和接收

如果 psutil 不能很好地与 UDP 配合使用,是否有替代解决方案

似乎 psutil 不是正确的解决方案和路径,结果发现 UDP 连接没有像 TCP 那样建立,所以我改用 python scapy 来捕获 UDP 数据包,它帮助我解决了目标 IP 地址