Python: how to get list of listen sockets in Linux

Here is an example of Python code to get listen socket from Python:

def listen_sockets():
    listens = []
    lines = open("/proc/net/tcp").readlines()
    for l in lines:
        ls = l.split()
        if ls[3] == '0A':
            lp =  ls[1].split(':')
            ip = str(lp[0])
            pair = "%s.%s.%s.%s:%s" %( int(ip[6:8], 16), int(ip[4:6], 16), int(ip[2:4], 16), int(ip[0:2], 16), int(lp[1], 16))
            listens.append(str(pair))
    return listenslistens = listen_sockets()
print listens
listens = listen_sockets()
print listens

Didn’t find the answer to your question? Ask it our administrators to reply we will publish on website.

Leave a Reply

Your email address will not be published. Required fields are marked *