赞
踩
一、介绍
平时发网络数据都是基于应用层的收发,如果要进行底层发送和接收必须使用另外的工具,这里以winpcap介绍tcpip底层的收发
二、安装包
pip install winpcapy
三、代码编写
1、导入库
from winpcapy import WinPcapUtils
2、发数据
arp_request_hex_template = "%(dst_mac)s%(src_mac)s08060001080006040001" \
"%(sender_mac)s%(sender_ip)s%(target_mac)s%(target_ip)s" + "00" * 18
packet = arp_request_hex_template % {
"dst_mac": "aa"*6,
"src_mac": "bb"*6,
"sender_mac": "bb"*6,
"target_mac": "cc"*6,
# 192.168.0.1
"sender_ip": "c0a80001",
# 192.168.0.2
"target_ip": "c0a80002"
}
# Send the packet (ethernet frame with an arp request) on the interface
WinPcapUtils.send_packet("*Ethernet*", bytes.fromhex(packet))
3、收数据
from winpcapy import WinPcapUtils
# Example Callback function to parse IP packets
def packet_callback(win_pcap, param, header, pkt_data):
# Assuming IP (for real parsing use modules like dpkt)
ip_frame = pkt_data[14:]
# Parse ips
src_ip = ".".join([str(ord(b)) for b in ip_frame[0xc:0x10]])
dst_ip = ".".join([str(ord(b)) for b in ip_frame[0x10:0x14]])
print("%s -> %s" % (src_ip, dst_ip))
WinPcapUtils.capture_on("*Ethernet*", packet_callback)
指定网卡名称
from winpcapy import WinPcap
device_name = '\\Device\\NPF_{AAAAAAAA-BBBB-CCCC-DDDD-EEEEEEEEEEEE}'
with WinPcap(device_name) as capture:
capture.send(bytes.fromhex('ff'*6))
git链接
https://github.com/orweis/winpcapy
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。