C# 基于SharpPcap的局域网数据包捕获 之二 监听代码
1.配置好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();
上面就是完整的选择网卡--开始监听--监听到包 的一个流程
---------------------
作者:wuma0q1an
来源:CSDN
原文:https://blog.csdn.net/wuma0q1an/article/details/50943235
版权声明:本文为博主原创文章,转载请附上博文链接!