Ajukilibodin
Ajukilibodin

Reputation: 35

Using Python to list all incoming connection in Linux

I'm trying to get Python to listen to my network and list all incoming connections as long as it runs. But I hit a brick wall and can't seem to find how. Any suggestions? Using Python 2.7.3

Upvotes: 1

Views: 4047

Answers (3)

tMC
tMC

Reputation: 19325

Your question is very vague on details but if all you want to do is watch inbound connections to your machine, you can do that with just a couple lines of python.

from socket import *

rawSocket = socket(AF_INET, SOCK_RAW, IPPROTO_TCP)
rawSocket.bind(('IP_ON_IFACE_TO_LISTEN_ON', 0))

while True:

    data = rawSocket.recv(2048)

    # http://en.wikipedia.org/wiki/IPv4#Packet_structure

    # Internet Header Length; Have to determine where the IP header ends
    ihl = ord(data[0]) & 15
    ip_payload = data[ihl*4:]

    # http://en.wikipedia.org/wiki/Transmission_Control_Protocol#TCP_segment_structure

    # Match SYN but not SYN/ACK
    if (ord(ip_payload[13]) & 18) == 2:
        src_addr = inet_ntoa(data[12:16])
        dst_addr = inet_ntoa(data[16:20])

        # Could use struct.unpack, might be clearer
        src_port = (ord(ip_payload[0]) << 8) + ord(ip_payload[1])
        dst_port = (ord(ip_payload[2]) << 8) + ord(ip_payload[3])

        src_str = (src_addr+':'+str(src_port)).ljust(22)
        dst_str = (dst_addr+':'+str(dst_port))

        print "%s=> %s" % (src_str, dst_str)

This will print all inbound TCP packets that have the SYN flag set, regardless of an RST or ICMP responses. Your question states 'list all incoming connections', since UDP is connectionless, I assume thats what you're asking about.

FWIW

Upvotes: 0

tink
tink

Reputation: 15204

@millimoose: I don't think (s)he needs/wants to listen on all sockets using python. What they're more likely after is Python bindings to libpcap

Upvotes: 2

nneonneo
nneonneo

Reputation: 179412

You can use netstat to list all incoming network connections. Someone has even written a Python implementation of netstat: http://voorloopnul.com/blog/a-python-netstat-in-less-than-100-lines-of-code/

Upvotes: 1

Related Questions