python基礎教程之擷取本機ip資料包樣本

來源:互聯網
上載者:User
這幾天用到了raw socket,用python寫了些demo程式,這裡記錄下。

首先我們看一個簡單的sniffer程式:

複製代碼 代碼如下:


#! /usr/bin/python
# code for linux
import socket
#s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_UDP)
s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_TCP)
while True:
print s.recvfrom(65535)

這裡直接用raw socket接收資料,直接print操作。這個就幾行代碼,也沒什麼好解釋的了,不懂的google下。

得到IP資料包後,接下來的工作就是對IP頭進行解析,在這之前,我們先看看RFC中是怎麼定義的(RFC791 : http://www.ietf.org/rfc/rfc791.txt ):

即對應的圖:


從RFC和中可以看到IP資料包頭各個欄位所佔的位元,我們可以根據這些定義去解析IP資料包頭,然後根據相應的策略處理資料。
這裡給出一段用python實現的解析IP頭的代碼(呵呵,是demo中的代碼,只解析了前20個位元組):

複製代碼 代碼如下:


def decodeIpHeader(packet):
mapRet = {}
mapRet["version"] = (int(ord(packet[0])) & 0xF0)>>4
mapRet["headerLen"] = (int(ord(packet[0])) & 0x0F)<<2
mapRet["serviceType"] = hex(int(ord(packet[1])))
mapRet["totalLen"] = (int(ord(packet[2])<<8))+(int(ord(packet[3])))
mapRet["identification"] = (int( ord(packet[4])>>8 )) + (int( ord(packet[5])))
mapRet["id"] = int(ord(packet[6]) & 0xE0)>>5
mapRet["fragOff"] = int(ord(packet[6]) & 0x1F)<<8 + int(ord(packet[7]))
mapRet["ttl"] = int(ord(packet[8]))
mapRet["protocol"] = int(ord(packet[9]))
mapRet["checkSum"] = int(ord(packet[10])<<8)+int(ord(packet[11]))
mapRet["srcaddr"] = "%d.%d.%d.%d" % (int(ord(packet[12])),int(ord(packet[13])),int(ord(packet[14])), int(ord(packet[15])))
mapRet["dstaddr"] = "%d.%d.%d.%d" % (int(ord(packet[16])),int(ord(packet[17])),int(ord(packet[18])), int(ord(packet[19])))
return mapRet

調用代碼:

複製代碼 代碼如下:


proto = socket.getprotobyname('tcp') # only tcp
sock = socket.socket(socket.AF_INET, socket.SOCK_RAW, proto)

while True:
packet = sock.recvfrom(65535)[0]
if len(packet) == 0:
sck.close()
else:
#print str(packet)
mapIpTmp = decodeIpHeader(packet)
for k,v in mapIpTmp.items():
print k,"\t:\t",v

print ""

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.