Search code examples
pythonpsutil

How do I list out the new TCP connections using Python?


I have a code which lists out all the tcp connections:

import psutil
for connection in (psutil.net_connections(kind='tcp')):
    print connection[5]

However, I need to list out the freshly added as well. I would, then, run the script which would run the code in the while(1) loop and keep on checking the new connections.


Solution

  • Save your connections in two different sets and compare them

    import psutil
    import time
    
    initial = frozenset(psutil.net_connections(kind='tcp'))
    while True:
        time.sleep(1)
        current = frozenset(psutil.net_connections(kind='tcp'))
        print(current.difference(initial))