Search code examples
pythonudppsutil

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


I am trying to get the destination IP (remote host) addresses connected to my machine that are using UDP protocol but i get Null results using psutil

the script I wrote

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()

The script works for TCP connections but gives nothing on UDP connections that are established on my local machine.

I read through psutil documentation however still cant figure out why it gives no results back on UDP

I can verify there are established UDP packets being sent and received using wireshark

if psutil does not work well with UDP is there an alternative solution


Solution

  • It seems like psutil was not the right solution and path to take, turned out UDP connections are not established like TCP, so instead I switched to python scapy to capture UDP packets and it helped me resolve the destination IP address