Raw socket has been used over the past few days, and some demo programs have been written in python, which is recorded here.
First, let's look at a simple sniffer program:
Copy codeThe Code is as follows:
#! /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)
Here, raw socket is used to receive data and print the data directly. This is just a few lines of code, and there is no good explanation, not understanding google.
After getting the IP packet, the next job is to parse the IP header, before that, we first look at how defined in RFC (RFC791: http://www.ietf.org/rfc/rfc791.txt ):
That is, the corresponding graph:
From the RFC and medium, we can see the number of digits occupied by each field in the IP address data packet header. We can parse the IP address data packet header according to these definitions and then process the data according to the corresponding policies.
Here is a piece of code for resolving the IP header implemented in python (haha, It is the code in the demo, only the first 20 bytes are parsed ):
Copy codeThe Code is as follows:
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
Call code:
Copy codeThe Code is as follows:
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 ""