国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁(yè) > 編程 > Python > 正文

python基礎(chǔ)教程之獲取本機(jī)ip數(shù)據(jù)包示例

2020-02-23 05:07:48
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(wǎng)友

這幾天用到了raw socket,用python寫(xiě)了些demo程序,這里記錄下。

首先我們看一個(gè)簡(jiǎn)單的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接收數(shù)據(jù),直接print操作。這個(gè)就幾行代碼,也沒(méi)什么好解釋的了,不懂的google下。

得到IP數(shù)據(jù)包后,接下來(lái)的工作就是對(duì)IP頭進(jìn)行解析,在這之前,我們先看看RFC中是怎么定義的(RFC791 : http://www.ietf.org/rfc/rfc791.txt ):

即對(duì)應(yīng)的圖:


從RFC和上圖中可以看到IP數(shù)據(jù)包頭各個(gè)字段所占的位數(shù),我們可以根據(jù)這些定義去解析IP數(shù)據(jù)包頭,然后根據(jù)相應(yīng)的策略處理數(shù)據(jù)。
這里給出一段用python實(shí)現(xiàn)的解析IP頭的代碼(呵呵,是demo中的代碼,只解析了前20個(gè)字節(jié)):

代碼如下:
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

調(diào)用代碼:

代碼如下:
proto = socket.getprotobyname('tcp') # only tcp
sock = socket.socket(socket.AF_INET, socket.SOCK_RAW, proto)

while True:
        packet = sock.recvfrom(65535)[0]

發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 民权县| 双峰县| 阿勒泰市| 四子王旗| 涞水县| 娱乐| 中阳县| 石林| 抚州市| 长武县| 定日县| 平阳县| 关岭| 汤阴县| 扶余县| 班戈县| 视频| 澜沧| 靖西县| 姜堰市| 宿迁市| 沙田区| 女性| 南靖县| 阜宁县| 宝兴县| 库尔勒市| 泽库县| 曲阳县| 那坡县| 兴国县| 开原市| 镇原县| 宜兰市| 栾川县| 天津市| 合肥市| 怀仁县| 德州市| 冀州市| 米脂县|