Jam*_*rtz 5 sockets raw-sockets python-3.x
我有一个使用 python 套接字的捕获包原始数据包:
s = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.ntohs(0x0003))
while True:
message = s.recv(4096)
test = []
print(len(message))
print(repr(message))
Run Code Online (Sandbox Code Playgroud)
我假设返回的数据包是十六进制字符串格式,但是打印出来的结果print(repr(message))是这样的:
b'\x00\x1b\xac\x00Gd\x00\x14\xd1+\x1f\x19\x05\n\x124VxC!UUUU\x00\x00\x00\x00\xcd\xcc\xcc=\xcd\xccL>\x9a\x99\x99>\xcd\xcc\xcc>\x00\x00\x00?\x9a\x......'
Run Code Online (Sandbox Code Playgroud)
它有奇怪的非十六进制字符,比如!UUUUor =。这是什么编码,如何解码数据包?
我现在提前知道数据包的样子,因为我是使用winpcapy生成数据包的人:
from ctypes import *
from winpcapy import *
import zlib
import binascii
import time
from ChanPackets import base, FrMessage, FrTodSync, FrChanConfig, FlChan, RlChan
while (1):
now = time.time()
errbuf = create_string_buffer(PCAP_ERRBUF_SIZE)
fp = pcap_t
deviceName = b'\\Device\\NPF_{8F5BD2E9-253F-4659-8256-B3BCD882AFBC}'
fp = pcap_open_live(deviceName, 65536, 1, 1000, errbuf)
if not bool(fp):
print ("\nUnable to open the adapter. %s is not supported by WinPcap\n" % deviceName)
sys.exit(2)
# FrMessage is a custom class that creates the packet
test = FrMessage('00:1b:ac:00:47:64', '00:14:d1:2b:1f:19', 0x12345678, 0x4321, 0x55555555, list(i/10 for i in range(320)))
# test.get_Raw_Packet() returns a c_bytes array needed for winpcap to send the packet
if (pcap_sendpacket(fp, test.get_Raw_Packet(), test.packet_size) != 0):
print ("\nError sending the packet: %s\n" % pcap_geterr(fp))
sys.exit(3)
elapsed = time.time() - now
if elapsed < 0.02 and elapsed > 0:
time.sleep(0.02 - elapsed)
pcap_close(fp)
Run Code Online (Sandbox Code Playgroud)
注意:我想获得一个表示每个字节的十六进制值数组
这是什么编码,如何解码数据包?
你看到的是bytesPython中对象的表示。正如您可能已经猜到的那样\xab表示字节0xab( 171)。
它有奇怪的非十六进制字符,如
!UUUU或=
可打印的 ASCII 字符表示它们自己,即,\x55表示只包含U.
你所拥有的是一个字节序列。如何解码它们取决于您的应用程序。例如,要解码包含以太网帧的数据包,您可以使用scapy(Python 2):
>>> b = '\x00\x02\x157\xa2D\x00\xae\xf3R\xaa\xd1\x08\x00E\x00\x00C\x00\x01\x00\x00@\x06x<\xc0\xa8\x05\x15B#\xfa\x97\x00\x14\x00P\x00\x00\x00\x00\x00\x00\x00\x00P\x02 \x00\xbb9\x00\x00GET /index.html HTTP/1.0 \n\n'
>>> c = Ether(b)
>>> c.hide_defaults()
>>> c
<Ether dst=00:02:15:37:a2:44 src=00:ae:f3:52:aa:d1 type=0x800 |
<IP ihl=5L len=67 frag=0 proto=tcp chksum=0x783c src=192.168.5.21 dst=66.35.250.151 |
<TCP dataofs=5L chksum=0xbb39 options=[] |
<Raw load='GET /index.html HTTP/1.0 \n\n' |>>>>
Run Code Online (Sandbox Code Playgroud)
我想获得一个表示每个字节的十六进制值数组
你可以使用binascii.hexlify():
>>> pkt = b'\x00\x1b\xac\x00Gd\x00'
>>> import binascii
>>> binascii.hexlify(pkt)
b'001bac00476400'
Run Code Online (Sandbox Code Playgroud)
或者如果你想要一个带有十六进制字符串值的列表:
>>> hexvalue = binascii.hexlify(pkt).decode()
>>> [hexvalue[i:i+2] for i in range(0, len(hexvalue), 2)]
['00', '1b', 'ac', '00', '47', '64', '00']
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
19901 次 |
| 最近记录: |