我试图让 Python 监听我的网络并列出所有传入的连接,只要它运行。但我撞到了一堵砖墙,似乎找不到怎么做。有什么建议么?使用 Python 2.7.3
			
			3451 次
		
3 回答
            2        
        
		
@millimoose:我不认为他需要/想要使用 python 监听所有套接字。他们更有可能的是 Python 绑定到 libpcap
于 2012-10-08T02:15:38.337   回答
    
    
            1        
        
		
您可以使用netstat列出所有传入的网络连接。甚至有人写了一个 Python 实现:http netstat: //voorloopnul.com/blog/a-python-netstat-in-less-than-100-lines-of-code/
于 2012-10-08T02:19:30.027   回答
    
    
            0        
        
		
您的问题在细节上非常含糊,但如果您只想查看与您的机器的入站连接,您只需几行 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)
这将打印所有设置了 SYN 标志的入站 TCP 数据包,无论 RST 或 ICMP 响应如何。您的问题是“列出所有传入连接”,因为 UDP 是无连接的,我认为这就是您要问的。
FWIW
于 2012-10-08T19:35:34.073   回答