2012-10-07 29 views
1

我試圖讓Python監聽我的網絡,並列出所有傳入連接,只要它運行。但是我撞到了一堵磚牆,似乎無法找到如何。有什麼建議麼?使用Python 2.7.3使用Python列出Linux中的所有傳入連接

+0

從這裏開始:http://docs.python.org/library/socket.html。也可能是一個基於C語言的套接字API教程,因爲Python標準庫對它進行了相當密切的反映。 (我不確定哪一個會很好,但我鏈接的文檔中提到了幾個。) – millimoose

+3

請詳細說明您碰到磚牆的位置。啓動python解釋器?尋找一個圖書館使用?使用庫? – Kevin

+3

您是否在談論只聽一個端口或讓您的python應用程序主動嗅探您的網絡? – Drahkar

回答

0

你的問題是細節非常模糊的,但如果你想要做的就是看你的機器的入站連接,你可以做到這一點只是蟒蛇的幾行。

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