当前位置: 移动技术网 > IT编程>开发语言>.net > C# 实现抓包的实例代码

C# 实现抓包的实例代码

2020年08月04日  | 移动技术网IT编程  | 我要评论
工具:sharppcap 4.2.0vs工程:控制台应用程序关于c#抓包,我只找到sharppcap 这个dll,相关的资料不多,而且都是挺老的,所以就顺手记一下自己的代码,给有同样需求的人一个参考吧

工具:sharppcap 4.2.0

vs工程:控制台应用程序

关于c#抓包,我只找到sharppcap 这个dll,相关的资料不多,而且都是挺老的,所以就顺手记一下自己的代码,给有同样需求的人一个参考吧。

当然,代码可能存在问题,请见谅。

一、获取连接设备

// 获取连接列表
capturedevicelist devices = capturedevicelist.instance;

// 无连接
if (devices.count < 1)
{
  console.writeline("no devices were found on this machine");
  return;
}

console.writeline("\n以下为本机连接:");
console.writeline("--------------\n");

int j=0;
string temp = "";
regex r = new regex("friendlyname: .*\n"); //匹配连接的friendlyname
match m;
// 打印连接设备
foreach (icapturedevice dev in devices)
{
  temp = dev.tostring();
  m = r.match(temp);
  console.writeline("{0}:{1}\n", j++, m.tostring());
}
console.write("输入设备号");
string input = console.readline();
int i = 0;
try
{
  i = int32.parse(input);
}
catch (exception e)
{
  console.writeline("非法输入!"+e.message);
  return;
}
if (devices.count < 1 || i == -1)
{
  console.writeline("变量非法!");
  return;
}
// 得到指定连接设备
icapturedevice device = devices[i];

二、打开连接

// 定义“包到达”事件
device.onpacketarrival +=new sharppcap.packetarrivaleventhandler(device_onpacketarrival);

// 打开连接
int readtimeoutmilliseconds = 1000;
device.open(devicemode.promiscuous, readtimeoutmilliseconds);

三、设置过滤

// 设置仅获取目标端口为1234的tcp包
string filter = "tcp dst port 1234";
device.filter = filter;

四、开始获取

// 开始无限期捕获包
device.capture();

五、包处理方法

private static void device_onpacketarrival(object sender, captureeventargs e)
{
  //获取以太网(ethernet)的帧
  var ent = packetdotnet.ethernetpacket.parsepacket(linklayers.ethernet, e.packet.data);
  //获取ip包
  var ip = ent.payloadpacket;
  //获取tcp包
  var tcp = ip.payloadpacket;
  //格式化tcp包,可直接读取tcp包中的相应值
  var tcp_packet = new tcppacket(new bytearraysegment(tcp.bytes));
  if (tcp != null)
  {
    datetime time = e.packet.timeval.date;
    if (tcp.payloaddata != null)
    {
      //根据需要,获取tcp的data数据
      string str = bitconverter.tostring(tcp.payloaddata);
      /*
      *
      其他数据处理
      *
      */
    }
  }
}

六、技术有限,只做到这样的程度

以上就是c# 实现抓包的实例代码的详细内容,更多关于c# 抓包的资料请关注移动技术网其它相关文章!

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网