版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
1、CONTENTSIntroduction2Background2About SharpPcap3Packet.Net architecture and usage4SharpPcap tutorial: A step by step guide to using SharpPcap6Obtaining the device list (Example 1 in the source package)6Opening an adapter and capturing packets (Example 3 in the source package)8Capturing packets witho
2、ut the event handler (Example 4 in the source package)10Filtering the traffic (Example 5 in the source package)11Interpreting the packets (Example 6 in the source package)12Handling offline dump files (Example 8 in the source package)14Sending packets (Example 9 in the source package)17Gathering sta
3、tistics on the network traffic - WinPcap only (Example 11 in the source package)21References23History23Eg:24A .NET sniffer application written with SharpPcapIntroductionPacket capturing (or packet sniffing) is the process of collecting all packets of data that pass through a given network interface.
4、 Capturing network packets in our applications is a powerful capability which lets us write network monitoring, packet analyzers and security tools. The libpcap library for UNIX based systems and WinPcap for Windows are the most widely used packet capture drivers that provide API for low-level netwo
5、rk monitoring. Among the applications that use libpcap/WinPcap as its packet capture subsystem are the famous tcpdump and Wireshark.In this article, we will introduce the SharpPcap .NET assembly (library) for interfacing with libpcap or winpcap from your .NET application and will give you a detailed
6、 programming tutorial on how to use it.BackgroundTamir Gal started the SharpPcap project around 2004. He wanted to use WinPcap in a .NET application while working on his final project for university. The project involved analyzing and decoding VoIP traffic and he wanted to keep coding simple with C#
7、 which has time saving features like garbage collection. Accessing the WinPcap API from .NET seemed to be quite a popular requirement, and he found some useful projects on CodeProjects website that let you do just that:o Packet Capture and Analayzer o Raw Socket Capturing Using C# o Packet sniffing
8、with winpcap functions ported to a .NET library The first project is a great ethereal .NET clone that lets you capture and analyze numerous types of protocol packets. However, a few issues with this project make it almost impossible to be shared among other .NET applications. Firstly, the author did
9、 not provide any generic API for capturing packets that can be used by other .NET applications. He didnt separate his UI code and his analyzing and capturing code, making his capturing code depend on the GUI classes such as ListView to operate. Secondly, for some reason the author chose to re-implem
10、ent some of WinPcaps functions in C# by himself rather than just wrapping them. This means that his application cant take advantage of the new WinPcap versions since he hard coded a certain version of WinPcap in his application.The second and the third articles are nice starts for wrapper projects f
11、or WinPcap, however they didnt provide some important WinPcap features such as handling offline pcap files and applying kernel-level packet filters, and most importantly they provide no parser classes for analyzing protocol packets. Both projects didnt post their library source code together with th
12、e article in order to let other people extend their work and add new features and new packet parser classes.And so, Tamir decided to start his own library for the task. Several versions in the 1.x series were released. Development slowed towards mid-2007 when the last version in the 1.x series was r
13、eleased, SharpPcap 1.6.2.Chris Morgan took over development of SharpPcap in November of 2008. Since then SharpPcap has had major internal rewrites and API improvements.In late February 2010 SharpPcap v3.0 was released. This release represents a rewrite of SharpPcaps packet parsers. Packet parsing fu
14、nctionality was broken out into a new library, Packet.Net. SharpPcap takes care of interfacing with libpcap/winpcap and Packet.Net takes care of packet dissection and creation. The details of Packet.Nets architecture will be discussed later in the turotial.About SharpPcapThe purpose of SharpPcap is
15、to provide a framework for capturing, injecting and analyzing network packets for .NET applications.SharpPcap is openly and actively developed with its source code and file releases hosted on SourceForge. Source code patches to improve or fix issues are welcome via the sharppcap developers mailing l
16、ist. Bug reports, feature requests and other queries are actively answered on the support forums and issue trackers there so if you have any trouble with the library please feel free to ask.SharpPcap is a fully managed cross platform library. The same assembly runs under Microsoft .NET as well as Mo
17、no on both 32 and 64bit platforms.The following list illustrates the features currently supported by SharpPcap:o Single assembly for Microsoft .NET and Mono platforms on Windows (32 or 64bit), Linux (32 or 64bit) and Mac. o High performance - SharpPcap can capture fast enough to keep up with +3MB/s
18、scp transfer rates o WinPcap extensions are partially supported Setting the kernel buffer size Injecting packets using send queues. Collecting network statistics on a given network interface o Enumerating and showing details about the physical network interface on a Windows machine. o Capturing low-
19、level network packets going through a given interface. o Analyzing and parsing the following protocols: Ethernet, Linux SLL ARP, IP (IPv4 and IPv6), TCP, UDP, ICMPv4, ICMPv6, IGMPv2, PPPoE, PTP, LLDP. o Injecting low-level network packets on a given interface. o Handling (reading and writing) offlin
20、e packet capture files. o Retrieving adapter statistics on packets received vs. dropped Please check the project homepage homepage for the latest updates and bug fixes.Packet.Net architecture and usageIf you are familiar with SharpPcap you may recall that SharpPcap used an inheritance model. Tcp pac
21、kets were represented by a class of type TCPPacket that inherited from IPPacket. IPPacket inherited from EthernetPacket and EthernetPacket inherited from the base packet class. This is convienent as each Tcp packet would have properties for Tcp fields, Ip fields and Ethernet fields. One API downside
22、 to this approach was field specific prefixes like TCPWindowSize and IPAddress, to clarify which fields went with which packet header.When users asked to be able to construct packets from values a significant issue became apparent. To build say a Udp packet a user needs to provide all of the fields
23、for the Udp packet, including payload, as well as those of all of the other inherited packets, the IP packet and Ethernet packet. This makes for more complex constructors and more complex internal code as headers for derived packets have to be preserved but their data overwritten with the encapsulat
24、ed packets header and data, ie. the IP packet payload is the Udp header and the Udp payload.Another issue with the inherited model is that it makes things like PPPoE difficult to represent as the PPPoE packet is inserted in the hierarchy. We no longer have the straight forward Ethernet-IP-Udp model,
25、 we now have Ethernet-PPPoE-PTP-IP-Udp. Its not clear how best to fit this kind of exception case into the inerhitance model.Packet.Net switches from an inheritance model to one of nesting packets. All packets contain a Packet PayloadPacket property and a Byte PayloadData property. One or neither of
26、 these can be valid. A Tcp packet captured on Ethernet may be EthernetPacket - IPv4 Packet - Tcp Packet. In Packet.Net the Tcp packet could be accessed like capturedPacket.PayloadPacket.PayloadPacket but to to aid users static GetEncapsulsted() methods have been added so users can do var tcpPacket =
27、 TcpPacket.GetEncapsulated(capturedPacket). The GetEncapsulated() methods are intelligent. They are designed to work in many different cases. UdpPacket.GetEncapsulated() will return the Udp packet of a packet that looks like EthernetPacket - IP packet - UdpPacket, Linux Cooked Capture - IP - UdpPack
28、et or EthernetPacket - PPPoE - PTP - IP - UdpPacket. We recommend using the GetEncapsulated() methods to retrieve sub packets vs writing your own code to do so. With Packet.Net constructing packets looks like: using PacketDotNet; ushort tcpSourcePort = 123; ushort tcpDestinationPort = 321; var tcpPa
29、cket = new TcpPacket(tcpSourcePort, tcpDestinationPort); var ipSourceAddress = System.Net.IPAddress.Parse(); var ipDestinationAddress = System.Net.IPAddress.Parse(); var ipPacket = new IPv4Packet(ipSourceAddress, ipDestinationAddress); var sourceHwAddress = 90-90-90-90-90-90; v
30、ar ethernetSourceHwAddress = System.Net.NetworkInformation.PhysicalAddress.Parse(sourceHwAddress); var destinationHwAddress = 80-80-80-80-80-80; var ethernetDestinationHwAddress = System.Net.NetworkInformation.PhysicalAddress.Parse(destinationHwAddress); / NOTE: using EthernetPacketType.None to illu
31、strate that the ethernet / protocol type is updated based on the packet payload that is / assigned to that particular ethernet packet var ethernetPacket = new EthernetPacket(ethernetSourceHwAddress, ethernetDestinationHwAddress, EthernetPacketType.None); / Now stitch all of the packets together ipPa
32、cket.PayloadPacket = tcpPacket; ethernetPacket.PayloadPacket = ipPacket; / and print out the packet to see that it looks just like we wanted it to Console.WriteLine(ethernetPacket.ToString();SharpPcap tutorial: A step by step guide to using SharpPcapExamples can be found in the Examples/ directory o
33、f the source package.The text of this tutorial was taken directly from WinPcaps official tutorial but is modified to show the C# use of the SharpPcap library. All examples can be downloaded together with the SharpPcap source code from the top of this page. If you are running on Windows, the WinPcap
34、library must be installed before attempting to run any of these examples so please download and install the latest version from WinPcaps download page. If running under unix/linux/mac the libpcap library must be installed using your systems software management system.The following topics are covered
35、 in this tutorial with the name of the example in parenthesis:13. Obtaining the device list (Example 1) 14. Opening an adapter and capturing packets (Example 3) 15. Capturing packets without the event (Example 4) 16. Filtering the traffic (Example 5) 17. Interpreting the packets (Example 6) 18. Hand
36、ling offline dump files (Example 8) 19. Sending packets (Example 9) 20. Gathering statistics on the network traffic (Example 11) 21. Queuing packets for background processing - High speed capture 22. Multiple Filters on device Obtaining the device list (Example 1 in the source package)Typically, the
37、 first thing that a SharpPcap-based application does is get a list of attached network adapters. SharpPcap provides a class, LivePcapDeviceList for this purpose. The class is a singleton instance that holds a cached list of network adapters of type LivePcapDevice. In particular, the Name and Descrip
38、tion properties contain the name and a human readable description, respectively, of the corresponding device. The following C# sample shows how to retrieve a list of adapters and print it on the screen, printing an error if no adapters are found:/ Print SharpPcap version string ver = SharpPcap.Versi
39、on.VersionString;Console.WriteLine(SharpPcap 0, Example1.IfList.cs, ver);/ Retrieve the device listLivePcapDeviceList devices = LivePcapDeviceList.Instance;/ If no devices were found print an errorif(devices.Count Example1.IfList.exeSharpPcap , Example1.IfList.csThe following devices are avai
40、lable on this machine:-interface: Name: DeviceNPF_D8B7C9B2-D53D-45DA-ACF0-2E2116F97314FriendlyName: Local Area Connection 2Description: Intel(R) PRO/1000 MT Desktop AdapterAddresses:Addr: fe80:b444:92d8:c882:8227Netmask:Broadaddr:Addresses:Addr: 5Netmask: Broadaddr: 255.255.255.
41、255Addresses:Addr: HW addr: 0800276AC792Flags: 0Hit Enter to exit.Opening an adapter and capturing packets (Example 3 in the source package)Now that weve seen how to obtain an adapter to play with, lets start the real job, opening an adapter and capturing some traffic. In this section, well write a
42、program that prints some information about each packet flowing through the adapter.The function that opens a device for capture is Open() which is overloaded with some arguments as follows:o Open() o Open(DeviceMode mode) o Open(DeviceMode mode, int read_timeout) The above two arguments deserve some
43、 further explanation.DeviceMode In normal mode (DeviceMode.Normal), a network adapter only captures packets addressed directly to it; the packets exchanged by other hosts on the network are ignored. Instead, when the adapter is in promiscuous mode (DeviceMode.Promiscuous) it captures all packets whe
44、ther they are destined to it or not. This means that on shared media (like non-switched Ethernet), libpcap/WinPcap will be able to capture the packets of other hosts. Promiscuous mode is the default for most capture applications, so we enable it in the following example. NOTE: Promiscuous mode can b
45、e detected via network means so if you are capturing in promiscuous mode you may be able to be detected by other entities on the network. Search for detect promiscuous via a web search engine for more information.read_timeout: Specifies the read timeout, in milliseconds. A read on the adapter (for e
46、xample, using the GetNextPacket() function) will always return after read_timeout milliseconds, even if no packets are available from the network. read_timeout also defines the interval between statistical reports if the adapter is in statistical mode (see the Gathering statistics on the network tra
47、ffic section). Setting read_timeout to 0 means no timeout, a read on the adapter never returns if no packets arrive. A -1 timeout on the other side causes a read on the adapter to always return immediately.The following example shows the use of the OnPacketArrival event for receiving packets. We cre
48、ate an event handler that is being called whenever a new packet is going through the PcapDevice:/ Extract a device from the list PcapDevice device = devicesi;/ Register our handler function to the / packet arrival event device.OnPacketArrival += new SharpPcap.PacketArrivalEventHandler(device_OnPacke
49、tArrival); / Open the device for capturing int readTimeoutMilliseconds = 1000; device.Open(DeviceMode.Promiscuous, readTimeoutMilliseconds);Console.WriteLine( - Listening on 0, hit Enter to stop., device.Description);/ Start the capturing process device.StartCapture();/ Wait for Enter from the user.
50、 Console.ReadLine(); / Stop the capturing process device.StopCapture();/ Close the pcap devicedevice.Close();And here is our packet handler implementation:/ / Prints the time and length of each received packet / private static void device_OnPacketArrival(object sender, CaptureEventArgs packet) DateT
51、ime time = packet.Timeval.Date; int len = packet.Data.Length; Console.WriteLine(0:1:2,3 Len=4, time.Hour, time.Minute, time.Second, time.Millisecond, len);Once the adapter is opened, the capture can be started with the StartCapture() or Capture(int packetCount) functions. These two functions are ver
52、y similar, the difference is that StartCapture() is a non-blocking function that starts the capturing process on a new thread, while Capture(int packetCount) blocks until packetCount packets have been captured. When using StartCapture() we should later call StopCapture() to terminate the capture pro
53、cess. To capture indefinitely call the Capture() method.Both of these functions require that an event handler for processing packets registered prior to calling them. This event handler is invoked by PcapDevice for every new packet coming from the network and receives the sender object that invoked
54、this handler (i.e. the PcapDevice object) and the actual received Packet, including all the protocol headers. Note that the frame CRC is normally not present in the packet, because it is removed by the network adapter after the frame validation. Note also that most adapters discard packets with wron
55、g CRCs, so WinPcap (and therefore SharpPcap) is normally not able to capture them.The Packet class represents a generic packet captured from the network. Each such packet has a PcapHeader property containing some info (e.g. the timestamp of the capture and the length of the packet) about the captured packet. The above example extracts the timestamp and the length from every Packet object and prints them on the screen.Please note that the handler code is c
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 邮轮相亲活动策划方案(3篇)
- 银行ATM防汛应急预案(3篇)
- 隧道接地扁铁施工方案(3篇)
- 26年指甲护理规范课件
- 主题教育调研报告格式-1
- 临床药学求职指南
- 合成氨转变工复试模拟考核试卷含答案
- 野生植物采集工岗前岗位安全责任制考核试卷含答案
- 纤维板铺装工安全规程知识考核试卷含答案
- 新教材人教版九年级物理习题课件第二十章 电与磁
- DL∕T 1084-2021 风力发电场噪声限值及测量方法
- 部编人教版《道德与法治》六年级下册期末测试卷加答案(夺冠系列)
- 编辑打印新课标高考英语词汇表3500词
- 带状疱疹疑难护理讨论
- 司炉与水处理安全技术培训课件
- 胸痛的护理查房
- 幕墙工程竣工资料(全套)
- 班级安全员培训课件-
- 承包商安全资格审查表格
- 残疾人旱地冰壶竞赛规则
- 煤矿绿色开采技术-课件
评论
0/150
提交评论