C# 基于SharpPcap的局域网数据包捕获 之二 监听代码https://blog.csdn.net/wuma0q1an/article/details/509432351.配置好sharpPcap引用和安装好winPcap后,添加引用
using PacketDotNet;
using SharpPcap;
using SharpPcap.AirPcap;
using SharpPcap.LibPcap;
using SharpPcap.WinPcap;
2.获取网卡,至于为什么会有两个注释掉的获取网卡方法。三种都可以获取到网卡,然而LibPcapLiveDeviceList获取网卡可以直观的看到它的名字,三种方法并没有多大区别(主要是忘记了实际区别)
private void getAdapter()//获取网卡
{
var devices = LibPcapLiveDeviceList.Instance;
//var devices = WinPcapDeviceList.Instance;
//var devices = CaptureDeviceList.Instance;
if (devices.Count < 1)
MessageBox.Show("此设备上没有网卡");
else
foreach (var dev in devices)
{
selectAdp.Items.Add(dev.Interface.FriendlyName);
selectAdp.SelectedIndex = 0;
}
}
3.开始监听,device_OnPackArrival是一个监听事件(方法),会在下面贴出。device.Open(DeviceMode.Promiscuous, 1000);是选择混淆模式监听
private void monitor()//监听
{
var devices = LibPcapLiveDeviceList.Instance;
//var devices = CaptureDeviceList.Instance;
foreach(PcapDevice dev in devices)
{
if (dev.Interface.FriendlyName.ToString() == selectedAdp)
{
//MessageBox.Show("pair");
PcapDevice device = dev;
device.OnPacketArrival += new PacketArrivalEventHandler(device_OnPackArrival);
device.Open(DeviceMode.Promiscuous, 1000);
//device.Capture(20);
device.StartCapture();
}
}
}
4.device_OnPackArrival方法
private void device_OnPackArrival(object sender,CaptureEventArgs e)//接收到包的处理
{
var packet = PacketDotNet.Packet.ParsePacket(e.Packet.LinkLayerType, e.Packet.Data);//解析出基本包
var dlpacket = PacketDotNet.DataLinkPacket.ParsePacket(e.Packet.LinkLayerType, e.Packet.Data);//协议类别
var ipPacket = PacketDotNet.IpPacket.GetEncapsulated(packet);//IP数据包
var udpPacket = PacketDotNet.UdpPacket.GetEncapsulated(packet);//UDP数据包
var tcpPacket = PacketDotNet.TcpPacket.GetEncapsulated(packet);//TCP数据包
//MessageBox.Show("????/");
if (IP.Checked)
//MessageBox.Show("tp");
showIPPacket(ipPacket);
else if (UDP.Checked)
// MessageBox.Show("UPD");
showUDPPacket(udpPacket);
else if (TCP.Checked)
showTCPPacket(tcpPacket);
}
5.packet包属性,部分属性如下
int srcPort = p.SourcePort;
int destPort = p.DestinationPort;
string details = p.ToString();
上面就是完整的选择网卡--开始监听--监听到包 的一个流程https://img-blog.csdnimg.cn/20190217105710569.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3UwMTEwNzgxNDE=,size_16,color_FFFFFF,t_70《算法导论 第三版英文版》_高清中文版.pdf
https://pan.baidu.com/s/17D1kXU6dLdU0YwHM2cvNMw
《深度学习入门:基于Python的理论与实现》_高清中文版.pdf
https://pan.baidu.com/s/1IeVs35f3gX5r6eAdiRQw4A
《深入浅出数据分析》_高清中文版.pdf
https://pan.baidu.com/s/1GV-QNbtmjZqumDkk8s7z5w
《Python编程:从入门到实践》_高清中文版.pdf
https://pan.baidu.com/s/1GUNSg4mdpeOf1LC_MjXunQ
《Python科学计算》_高清中文版.pdf
https://pan.baidu.com/s/1-hDKhK-7rDDFll_UFpKmpw