您的位置:首页 > 理论基础 > 计算机网络

使用SharpPCap在C#下进行网络抓包

2010-11-05 17:31 375 查看
转自/article/5726364.html

在做大学最后的毕业设计了,无线局域网络远程安全监控策略
那么抓包是这个系统设计的基础
以前一直都是知道用winpcap的,现在网上搜了一下,有用C#封装好了的,很好用
下面是其中的几个用法
这个类库作者的主页:http://www.tamirgal.com/home/default.aspx

PcapOpen()有下面几个方法

PcapOpen()

PcapOpen(boolpromiscuous_mode)

PcapOpen(boolpromiscuous_mode,intread_timeout)

promiscuous_mode:在普通的抓取模式下,我们只抓取那些目的地为目标网络的包,而处于promiscuous_mode时,则抓取所有的包,包括转发的包.通常我们都是开启这种模式的

下面是示例:

//Extractadevicefromthelist

PcapDevicedevice=devices[i];

//Registerourhandlerfunctiontothe

//'packetarrival'event

device.PcapOnPacketArrival+=

newSharpPcap.PacketArrivalEvent(device_PcapOnPacketArrival);

//Openthedeviceforcapturing

//true--meanspromiscuousmode

//1000--meansareadwaitof1000ms

device.PcapOpen(true,1000);

Console.WriteLine(

"--Listenningon{0},hit'Enter'tostop...",

device.PcapDescription);

//Startthecapturingprocess

device.PcapStartCapture();

//Waitfor'Enter'fromtheuser.

Console.ReadLine();

//Stopthecapturingprocess

device.PcapStopCapture();

//Closethepcapdevice
device.PcapClose();

PcapStartCapture()
对应PcapStopCapture()


使用PcapCapture(
int
packetCount)
时我们可以使用
SharpPcap.INFINITE,
来达到持续抓包的功能


Note:通常CRC的数据是不在数据包的中的,因为通常错误的CRC包会被自动丢弃.

上面的需要注册一个eventhandle,这在很多时候是不可行的,所以我们推荐使用下面这个方法PcapGetNextPacket()




//Extractadevicefromthelist

PcapDevicedevice=devices[i];

//Openthedeviceforcapturing
//true--meanspromiscuousmode
//1000--meansareadwaitof1000ms
device.PcapOpen(true,1000);
Console.WriteLine();
Console.WriteLine("--Listenningon{0}...",
device.PcapDescription);
Packetpacket=null;

//KeepcapturepacketsusingPcapGetNextPacket()
while((packet=device.PcapGetNextPacket())!=null)

//Closethepcapdevice

device.PcapClose();

Console.WriteLine("--Capturestopped,deviceclosed.");

PcapSetFilter()
设置过滤条件




stringfilter="ipandtcp";

device.PcapSetFilter(filter);


下面这个例子通过抓取TCP包,输出他们的时间,长度,源IP,源端口,目的IP,目的端口

privatestaticvoiddevice_PcapOnPacketArrival(
objectsender,Packetpacket)

{




if(packetisTCPPacket)






{




DateTimetime=packet.Timeval.Date;




intlen=packet.PcapHeader.len;








TCPPackettcp=(TCPPacket)packet;




stringsrcIp=tcp.SourceAddress;




stringdstIp=tcp.DestinationAddress;




intsrcPort=tcp.SourcePort;




intdstPort=tcp.DestinationPort;








Console.WriteLine("{0}:{1}:{2},






{3}Len={4}{5}:{6}->{7}:{8}",




time.Hour,time.Minute,time.Second,




time.Millisecond,len,srcIp,srcPort,




dstIp,dstPort);




}




}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: