
這幾天用到了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 ""
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com