Home Backend Development Python Tutorial python基础教程之获取本机ip数据包示例

python基础教程之获取本机ip数据包示例

Jun 16, 2016 am 08:45 AM
local machine

这几天用到了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 ):

python基础教程之获取本机ip数据包示例

即对应的图:

python基础教程之获取本机ip数据包示例

从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)        mapRet["serviceType"] = hex(int(ord(packet[1])))
        mapRet["totalLen"] = (int(ord(packet[2])        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)        mapRet["ttl"] = int(ord(packet[8]))
        mapRet["protocol"] = int(ord(packet[9]))
        mapRet["checkSum"] = int(ord(packet[10])        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 ""

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? Apr 02, 2025 am 07:15 AM

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

How to solve permission issues when using python --version command in Linux terminal? How to solve permission issues when using python --version command in Linux terminal? Apr 02, 2025 am 06:36 AM

Using python in Linux terminal...

How to teach computer novice programming basics in project and problem-driven methods within 10 hours? How to teach computer novice programming basics in project and problem-driven methods within 10 hours? Apr 02, 2025 am 07:18 AM

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How to get news data bypassing Investing.com's anti-crawler mechanism? How to get news data bypassing Investing.com's anti-crawler mechanism? Apr 02, 2025 am 07:03 AM

Understanding the anti-crawling strategy of Investing.com Many people often try to crawl news data from Investing.com (https://cn.investing.com/news/latest-news)...

Python 3.6 loading pickle file error ModuleNotFoundError: What should I do if I load pickle file '__builtin__'? Python 3.6 loading pickle file error ModuleNotFoundError: What should I do if I load pickle file '__builtin__'? Apr 02, 2025 am 06:27 AM

Loading pickle file in Python 3.6 environment error: ModuleNotFoundError:Nomodulenamed...

What is the reason why pipeline files cannot be written when using Scapy crawler? What is the reason why pipeline files cannot be written when using Scapy crawler? Apr 02, 2025 am 06:45 AM

Discussion on the reasons why pipeline files cannot be written when using Scapy crawlers When learning and using Scapy crawlers for persistent data storage, you may encounter pipeline files...

See all articles