Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

updated SharpPcap to 3.6.0

  • Loading branch information...
commit 65498c113972c14078d9efd45da6baee2545f480 1 parent 9cf405d
seuffert authored
Showing with 743 additions and 3,576 deletions.
  1. +1 −1  SharpPcap/ARP.cs
  2. +9 −9 SharpPcap/AirPcap/AirPcapDevice.cs
  3. +1 −1  SharpPcap/AssemblyInfo.cs
  4. +4 −4 SharpPcap/CaptureEventArgs.cs
  5. +0 −42 SharpPcap/CaptureMode.cs
  6. +7 −2 SharpPcap/ICaptureDevice.cs
  7. +20 −0 SharpPcap/LibPcap/LibPcapLiveDevice.cs
  8. +0 −23 SharpPcap/LibPcap/LibPcapLiveDeviceList.cs
  9. +47 −13 SharpPcap/LibPcap/PcapDevice.cs
  10. +0 −330 SharpPcap/LivePcapDevice.cs
  11. +0 −232 SharpPcap/LivePcapDeviceList.cs
  12. +0 −125 SharpPcap/OfflinePcapDevice.cs
  13. +0 −92 SharpPcap/PcapAddress.cs
  14. +0 −622 SharpPcap/PcapDevice.cs
  15. +0 −399 SharpPcap/PcapDeviceCaptureLoop.cs
  16. +0 −172 SharpPcap/PcapHeader.cs
  17. +0 −182 SharpPcap/PcapInterface.cs
  18. +0 −126 SharpPcap/PcapStatistics.cs
  19. +0 −293 SharpPcap/PcapUnmanagedStructures.cs
  20. +296 −0 SharpPcap/PosixTimeval.cs
  21. +90 −0 SharpPcap/RawCapture.cs
  22. +0 −302 SharpPcap/SafeNativeMethods.cs
  23. +0 −196 SharpPcap/SendQueue.cs
  24. +0 −41 SharpPcap/SendQueueTransmitModes.cs
  25. +2 −0  SharpPcap/SharpPcap.csproj
  26. +0 −13 SharpPcap/SharpPcap.csproj.user
  27. +0 −173 SharpPcap/Sockaddr.cs
  28. +0 −56 SharpPcap/StatisticsModeEventArgs.cs
  29. +0 −31 SharpPcap/StatisticsModeEventHandler.cs
  30. +0 −74 SharpPcap/StatisticsModePacket.cs
  31. +1 −1  SharpPcap/WinPcap/SendQueue.cs
  32. +2 −2 SharpPcap/WinPcap/StatisticsModeEventArgs.cs
  33. +2 −2 SharpPcap/WinPcap/StatisticsModePacket.cs
  34. +27 −2 SharpPcap/WinPcap/WinPcapDevice.cs
  35. +234 −15 SharpPcap/docs/Api/SharpPcap.xml
2  SharpPcap/ARP.cs
View
@@ -224,7 +224,7 @@ public PhysicalAddress Resolve(System.Net.IPAddress destIP, string deviceName)
}
// parse the packet
- var packet = PacketDotNet.Packet.ParsePacket(reply);
+ var packet = PacketDotNet.Packet.ParsePacket(reply.LinkLayerType, reply.Data);
// is this an arp packet?
arpPacket = PacketDotNet.ARPPacket.GetEncapsulated(packet);
18 SharpPcap/AirPcap/AirPcapDevice.cs
View
@@ -685,7 +685,7 @@ public override PacketDotNet.LinkLayers LinkType
/// <summary>
/// Mac address
/// </summary>
- public PhysicalAddress MacAddress
+ public override PhysicalAddress MacAddress
{
get
{
@@ -885,7 +885,7 @@ protected override void CaptureThread()
UInt32 BytesReceived;
- List<PacketDotNet.RawPacket> packets;
+ List<RawCapture> packets;
while (!shouldCaptureThreadStop)
{
@@ -924,13 +924,13 @@ protected override void CaptureThread()
/// <param name="bufferEnd"></param>
/// <param name="packets"></param>
protected virtual void MarshalPackets(IntPtr packetsBuffer, IntPtr bufferEnd,
- out List<PacketDotNet.RawPacket> packets)
+ out List<RawCapture> packets)
{
- PacketDotNet.RawPacket p;
+ RawCapture p;
var linkType = LinkType;
- packets = new List<PacketDotNet.RawPacket>();
+ packets = new List<RawCapture>();
IntPtr bufferPointer = packetsBuffer;
@@ -945,10 +945,10 @@ protected override void CaptureThread()
var pkt_data = new byte[header.Caplen];
Marshal.Copy(bufferPointer, pkt_data, 0, (int)header.Caplen);
- p = new PacketDotNet.RawPacket(linkType,
- new PacketDotNet.PosixTimeval(header.TsSec,
- header.TsUsec),
- pkt_data);
+ p = new RawCapture(linkType,
+ new PosixTimeval(header.TsSec,
+ header.TsUsec),
+ pkt_data);
packets.Add(p);
2  SharpPcap/AssemblyInfo.cs
View
@@ -25,7 +25,7 @@
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
-[assembly: AssemblyVersion("3.5.0")]
+[assembly: AssemblyVersion("3.6.0")]
//
// In order to sign your assembly you must specify a key to use. Refer to the
8 SharpPcap/CaptureEventArgs.cs
View
@@ -28,12 +28,12 @@ namespace SharpPcap
/// </summary>
public class CaptureEventArgs : EventArgs
{
- private PacketDotNet.RawPacket packet;
+ private RawCapture packet;
/// <summary>
/// Packet that was captured
/// </summary>
- public PacketDotNet.RawPacket Packet
+ public RawCapture Packet
{
get { return packet; }
}
@@ -52,12 +52,12 @@ public ICaptureDevice Device
/// Constructor
/// </summary>
/// <param name="packet">
- /// A <see cref="PacketDotNet.RawPacket"/>
+ /// A <see cref="RawCapture"/>
/// </param>
/// <param name="device">
/// A <see cref="ICaptureDevice"/>
/// </param>
- public CaptureEventArgs(PacketDotNet.RawPacket packet, ICaptureDevice device)
+ public CaptureEventArgs(RawCapture packet, ICaptureDevice device)
{
this.packet = packet;
this.device = device;
42 SharpPcap/CaptureMode.cs
View
@@ -1,42 +0,0 @@
-/*
-This file is part of SharpPcap.
-
-SharpPcap is free software: you can redistribute it and/or modify
-it under the terms of the GNU Lesser General Public License as published by
-the Free Software Foundation, either version 3 of the License, or
-(at your option) any later version.
-
-SharpPcap is distributed in the hope that it will be useful,
-but WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-GNU Lesser General Public License for more details.
-
-You should have received a copy of the GNU Lesser General Public License
-along with SharpPcap. If not, see <http://www.gnu.org/licenses/>.
-*/
-/*
- * Copyright 2010 Chris Morgan <chmorgan@gmail.com>
- */
-
-using System;
-
-namespace SharpPcap
-{
- /// <summary>
- /// The working mode of a Pcap device
- /// </summary>
- public enum CaptureMode : int
- {
- /// <summary>
- /// Set a Pcap device to capture packets, Capture mode
- /// </summary>
- Packets = 0,
-
- /// <summary>
- /// Set a Pcap device to report statistics.
- /// <br/>
- /// Statistics mode is only supported in WinPcap
- /// </summary>
- Statistics = 1
- };
-}
9 SharpPcap/ICaptureDevice.cs
View
@@ -53,6 +53,11 @@ public interface ICaptureDevice
/// </summary>
ICaptureStatistics Statistics { get; }
+ /// <summary>
+ /// Mac address of the physical device
+ /// </summary>
+ System.Net.NetworkInformation.PhysicalAddress MacAddress { get; }
+
#region Dump related
/// <summary>
/// Gets a value indicating whether a dump file is already associated with this device
@@ -63,7 +68,7 @@ public interface ICaptureDevice
/// Writes a packet to the pcap dump file associated with this device.
/// </summary>
/// <param name="p">The packet to write</param>
- void Dump(PacketDotNet.RawPacket p);
+ void Dump(RawCapture p);
/// <summary>
/// Opens a file for packet writings
@@ -156,7 +161,7 @@ public interface ICaptureDevice
/// Retrieves the next packet from a device
/// </summary>
/// <returns></returns>
- PacketDotNet.RawPacket GetNextPacket();
+ RawCapture GetNextPacket();
/// <summary>
/// Sends a raw packet throgh this device
20 SharpPcap/LibPcap/LibPcapLiveDevice.cs
View
@@ -41,6 +41,26 @@ public class LibPcapLiveDevice : PcapDevice
internal LibPcapLiveDevice( PcapInterface pcapIf )
{
m_pcapIf = pcapIf;
+
+ // go through the network interfaces and attempt to populate the mac address,
+ // friendly name etc of this device
+ NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
+ foreach (NetworkInterface adapter in nics)
+ {
+ // if the name and id match then we have found the NetworkInterface
+ // that matches the PcapDevice
+ if (Name.EndsWith(adapter.Id))
+ {
+ var ipProperties = adapter.GetIPProperties();
+ if (ipProperties.GatewayAddresses.Count != 0)
+ {
+ Interface.GatewayAddress = ipProperties.GatewayAddresses[0].Address;
+ }
+
+ Interface.MacAddress = adapter.GetPhysicalAddress();
+ Interface.FriendlyName = adapter.Name;
+ }
+ }
}
/// <summary>
23 SharpPcap/LibPcap/LibPcapLiveDeviceList.cs
View
@@ -104,29 +104,6 @@ private static List<LibPcapLiveDevice> GetDevices()
}
LibPcapSafeNativeMethods.pcap_freealldevs(devicePtr); // Free unmanaged memory allocation.
- // go through the network interfaces to populate the mac address
- // for each of the devices
- NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
- foreach(LibPcapLiveDevice device in deviceList)
- {
- foreach(NetworkInterface adapter in nics)
- {
- // if the name and id match then we have found the NetworkInterface
- // that matches the PcapDevice
- if(device.Name.EndsWith(adapter.Id))
- {
- var ipProperties = adapter.GetIPProperties();
- if (ipProperties.GatewayAddresses.Count != 0)
- {
- device.Interface.GatewayAddress = ipProperties.GatewayAddresses[0].Address;
- }
-
- device.Interface.MacAddress = adapter.GetPhysicalAddress();
- device.Interface.FriendlyName = adapter.Name;
- }
- }
- }
-
return deviceList;
}
60 SharpPcap/LibPcap/PcapDevice.cs
View
@@ -68,6 +68,22 @@ public abstract partial class PcapDevice : ICaptureDevice
public event PacketArrivalEventHandler OnPacketArrival;
/// <summary>
+ /// Implemented because there isn't any way to perform
+ /// if(OnPacketArrival == null) isn't permitted outside of the containing class
+ /// this operation results in a CS0070 compile error
+ /// </summary>
+ /// <returns>
+ /// A <see cref="System.Boolean"/>
+ /// </returns>
+ internal bool IsOnPacketArrivalNull
+ {
+ get
+ {
+ return (OnPacketArrival == null);
+ }
+ }
+
+ /// <summary>
/// Fired when the capture process of this pcap device is stopped
/// </summary>
public event CaptureStoppedEventHandler OnCaptureStopped;
@@ -204,12 +220,30 @@ public virtual void Close()
public abstract ICaptureStatistics Statistics { get; }
/// <summary>
+ /// Mac address of the physical device
+ /// </summary>
+ public virtual System.Net.NetworkInformation.PhysicalAddress MacAddress
+ {
+ get
+ {
+ ThrowIfNotOpen("device not open");
+
+ return Interface.MacAddress;
+ }
+
+ set
+ {
+ throw new System.NotImplementedException();
+ }
+ }
+
+ /// <summary>
/// Notify the OnPacketArrival delegates about a newly captured packet
/// </summary>
/// <param name="p">
- /// A <see cref="PacketDotNet.RawPacket"/>
+ /// A <see cref="RawCapture"/>
/// </param>
- protected void SendPacketArrivalEvent(PacketDotNet.RawPacket p)
+ protected void SendPacketArrivalEvent(RawCapture p)
{
var handler = OnPacketArrival;
if(handler != null )
@@ -238,9 +272,9 @@ protected void SendCaptureStoppedEvent(CaptureStoppedEventStatus status)
/// Gets the next packet captured on this device
/// </summary>
/// <returns>The next packet captured on this device</returns>
- public virtual PacketDotNet.RawPacket GetNextPacket()
+ public virtual RawCapture GetNextPacket()
{
- PacketDotNet.RawPacket p;
+ RawCapture p;
int res = GetNextPacket( out p );
if(res==-1)
throw new PcapException("Error receiving packet.");
@@ -251,12 +285,12 @@ public virtual PacketDotNet.RawPacket GetNextPacket()
/// Gets the next packet captured on this device
/// </summary>
/// <param name="p">
- /// A <see cref="PacketDotNet.RawPacket"/>
+ /// A <see cref="RawCapture"/>
/// </param>
/// <returns>
/// A <see cref="System.Int32"/> that contains the result code
/// </returns>
- public virtual int GetNextPacket(out PacketDotNet.RawPacket p)
+ public virtual int GetNextPacket(out RawCapture p)
{
//Pointer to a packet info struct
IntPtr header = IntPtr.Zero;
@@ -314,11 +348,11 @@ protected virtual void PacketHandler(IntPtr param, IntPtr /* pcap_pkthdr* */ hea
/// A <see cref="IntPtr"/>
/// </param>
/// <returns>
- /// A <see cref="PacketDotNet.RawPacket"/>
+ /// A <see cref="RawCapture"/>
/// </returns>
- protected virtual PacketDotNet.RawPacket MarshalRawPacket(IntPtr /* pcap_pkthdr* */ header, IntPtr data)
+ protected virtual RawCapture MarshalRawPacket(IntPtr /* pcap_pkthdr* */ header, IntPtr data)
{
- PacketDotNet.RawPacket p;
+ RawCapture p;
// marshal the header
var pcapHeader = new PcapHeader(header);
@@ -326,9 +360,9 @@ protected virtual PacketDotNet.RawPacket MarshalRawPacket(IntPtr /* pcap_pkthdr*
var pkt_data = new byte[pcapHeader.CaptureLength];
Marshal.Copy(data, pkt_data, 0, (int)pcapHeader.CaptureLength);
- p = new PacketDotNet.RawPacket(LinkType,
- new PacketDotNet.PosixTimeval(pcapHeader.Seconds,
- pcapHeader.MicroSeconds),
+ p = new RawCapture(LinkType,
+ new PosixTimeval(pcapHeader.Seconds,
+ pcapHeader.MicroSeconds),
pkt_data);
return p;
@@ -413,7 +447,7 @@ public void Dump(byte[] p)
/// Writes a packet to the pcap dump file associated with this device.
/// </summary>
/// <param name="p">The packet to write</param>
- public void Dump(PacketDotNet.RawPacket p)
+ public void Dump(RawCapture p)
{
var data = p.Data;
var timeval = p.Timeval;
330 SharpPcap/LivePcapDevice.cs
View
@@ -1,330 +0,0 @@
-/*
-This file is part of SharpPcap.
-
-SharpPcap is free software: you can redistribute it and/or modify
-it under the terms of the GNU Lesser General Public License as published by
-the Free Software Foundation, either version 3 of the License, or
-(at your option) any later version.
-
-SharpPcap is distributed in the hope that it will be useful,
-but WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-GNU Lesser General Public License for more details.
-
-You should have received a copy of the GNU Lesser General Public License
-along with SharpPcap. If not, see <http://www.gnu.org/licenses/>.
-*/
-/*
- * Copyright 2005 Tamir Gal <tamir@tamirgal.com>
- * Copyright 2008-2009 Chris Morgan <chmorgan@gmail.com>
- * Copyright 2008-2010 Phillip Lemon <lucidcomms@gmail.com>
- */
-
-using System;
-using System.Text;
-using System.Collections.ObjectModel;
-using System.Net.NetworkInformation;
-using System.Runtime.InteropServices;
-using System.Diagnostics;
-
-namespace SharpPcap
-{
- /// <summary>
- /// Capture live packets from a network device
- /// </summary>
- public class LivePcapDevice : PcapDevice
- {
- /// <summary>
- /// Constructs a new PcapDevice based on a 'pcapIf' struct
- /// </summary>
- /// <param name="pcapIf">A 'pcapIf' struct representing
- /// the pcap device</param>
- internal LivePcapDevice( PcapInterface pcapIf )
- {
- m_pcapIf = pcapIf;
- }
-
- /// <summary>
- /// Default contructor for subclasses
- /// </summary>
- protected LivePcapDevice()
- {
- }
-
- /// <summary>
- /// PcapDevice finalizer. Ensure PcapDevices are stopped and closed before exit.
- /// </summary>
- ~LivePcapDevice()
- {
- this.Close();
- }
-
- /// <summary>
- /// Gets the pcap name of this network device
- /// </summary>
- public override string Name
- {
- get { return m_pcapIf.Name; }
- }
-
- /// <summary>
- /// Addresses that represent this device
- /// </summary>
- public virtual ReadOnlyCollection<PcapAddress> Addresses
- {
- get { return new ReadOnlyCollection<PcapAddress>(m_pcapIf.Addresses); }
- }
-
- /// <summary>
- /// Gets the pcap description of this device
- /// </summary>
- public override string Description
- {
- get { return m_pcapIf.Description; }
- }
-
- /// <summary>
- /// Interface flags, see pcap_findalldevs() man page for more info
- /// </summary>
- public virtual uint Flags
- {
- get { return m_pcapIf.Flags; }
- }
-
- /// <summary>
- /// True if device is a loopback interface, false if not
- /// </summary>
- public virtual bool Loopback
- {
- get { return (Flags & Pcap.PCAP_IF_LOOPBACK)==1; }
- }
-
- /// <summary>
- /// Open the device with default values of: promiscuous_mode = false, read_timeout = 1000
- /// To start capturing call the 'StartCapture' function
- /// </summary>
- public override void Open()
- {
- this.Open(DeviceMode.Normal);
- }
-
- /// <summary>
- /// Open the device. To start capturing call the 'StartCapture' function
- /// </summary>
- /// <param name="mode">
- /// A <see cref="DeviceMode"/>
- /// </param>
- public virtual void Open(DeviceMode mode)
- {
- const int readTimeoutMilliseconds = 1000;
- this.Open(mode, readTimeoutMilliseconds);
- }
-
- /// <summary>
- /// Open the device. To start capturing call the 'StartCapture' function
- /// </summary>
- /// <param name="mode">
- /// A <see cref="DeviceMode"/>
- /// </param>
- /// <param name="read_timeout">
- /// A <see cref="System.Int32"/>
- /// </param>
- public virtual void Open(DeviceMode mode, int read_timeout)
- {
- if ( !Opened )
- {
- StringBuilder errbuf = new StringBuilder( Pcap.PCAP_ERRBUF_SIZE ); //will hold errors
-
- PcapHandle = SafeNativeMethods.pcap_open_live
- ( Name, // name of the device
- Pcap.MAX_PACKET_SIZE, // portion of the packet to capture.
- // MAX_PACKET_SIZE (65536) grants that the whole packet will be captured on all the MACs.
- (short)mode, // promiscuous mode
- (short)read_timeout, // read timeout
- errbuf ); // error buffer
-
- if ( PcapHandle == IntPtr.Zero)
- {
- string err = "Unable to open the adapter ("+Name+"). "+errbuf.ToString();
- throw new PcapException( err );
- }
- }
- }
-
- private const int disableBlocking = 0;
- private const int enableBlocking = 1;
-
- /// <summary>
- /// Set/Get Non-Blocking Mode. returns allways false for savefiles.
- /// </summary>
- public bool NonBlockingMode
- {
- get
- {
- var errbuf = new StringBuilder(Pcap.PCAP_ERRBUF_SIZE); //will hold errors
- int ret = SafeNativeMethods.pcap_getnonblock(PcapHandle, errbuf);
-
- // Errorbuf is only filled when ret = -1
- if (ret == -1)
- {
- string err = "Unable to set get blocking" + errbuf.ToString();
- throw new PcapException(err);
- }
-
- if(ret == enableBlocking)
- return true;
- return false;
- }
- set
- {
- var errbuf = new StringBuilder(Pcap.PCAP_ERRBUF_SIZE); //will hold errors
-
- int block = disableBlocking;
- if (value)
- block = enableBlocking;
-
- int ret = SafeNativeMethods.pcap_setnonblock(PcapHandle, block, errbuf);
-
- // Errorbuf is only filled when ret = -1
- if (ret == -1)
- {
- string err = "Unable to set non blocking" + errbuf.ToString();
- throw new PcapException(err);
- }
- }
- }
-
- /// <summary>
- /// Sends a raw packet throgh this device
- /// </summary>
- /// <param name="p">The packet to send</param>
- public void SendPacket(PacketDotNet.Packet p)
- {
- SendPacket(p.Bytes);
- }
-
-
- /// <summary>
- /// Sends a raw packet throgh this device
- /// </summary>
- /// <param name="p">The packet to send</param>
- /// <param name="size">The number of bytes to send</param>
- public void SendPacket(PacketDotNet.Packet p, int size)
- {
- SendPacket(p.Bytes, size);
- }
-
- /// <summary>
- /// Sends a raw packet throgh this device
- /// </summary>
- /// <param name="p">The packet bytes to send</param>
- public void SendPacket(byte[] p)
- {
- SendPacket(p, p.Length);
- }
-
- /// <summary>
- /// Sends a raw packet throgh this device
- /// </summary>
- /// <param name="p">The packet bytes to send</param>
- /// <param name="size">The number of bytes to send</param>
- public void SendPacket(byte[] p, int size)
- {
-
- ThrowIfNotOpen("Can't send packet, the device is closed");
-
- if (size > p.Length)
- {
- throw new ArgumentException("Invalid packetSize value: "+size+
- "\nArgument size is larger than the total size of the packet.");
- }
-
- if (p.Length > Pcap.MAX_PACKET_SIZE)
- {
- throw new ArgumentException("Packet length can't be larger than "+Pcap.MAX_PACKET_SIZE);
- }
-
- IntPtr p_packet = IntPtr.Zero;
- p_packet = Marshal.AllocHGlobal( size );
- Marshal.Copy(p, 0, p_packet, size);
-
- int res = SafeNativeMethods.pcap_sendpacket(PcapHandle, p_packet, size);
- Marshal.FreeHGlobal(p_packet);
- if(res < 0)
- {
- throw new PcapException("Can't send packet: " + LastError);
- }
- }
-
- /// <summary>
- /// Sends all packets in a 'PcapSendQueue' out this pcap device
- /// </summary>
- /// <param name="q">
- /// A <see cref="SendQueue"/>
- /// </param>
- /// <param name="transmitMode">
- /// A <see cref="SendQueueTransmitModes"/>
- /// </param>
- /// <returns>
- /// A <see cref="System.Int32"/>
- /// </returns>
- public int SendQueue( SendQueue q, SendQueueTransmitModes transmitMode )
- {
- return q.Transmit( this, transmitMode);
- }
-
- /// <summary>
- /// Retrieves pcap statistics
- /// </summary>
- /// <returns>
- /// A <see cref="PcapStatistics"/>
- /// </returns>
- public override PcapStatistics Statistics()
- {
- // can only call PcapStatistics on an open device
- ThrowIfNotOpen("device not open");
-
- return new PcapStatistics(this.m_pcapAdapterHandle);
- }
-
- /// <value>
- /// Set the kernel value buffer size in bytes
- /// WinPcap extension
- /// </value>
- public int KernelBufferSize
- {
- set
- {
- ThrowIfNotWinPcap();
- ThrowIfNotOpen("Can't set kernel buffer size, the device is not opened");
-
- int retval = SafeNativeMethods.pcap_setbuff(this.m_pcapAdapterHandle,
- value);
- if(retval != 0)
- {
- throw new System.InvalidOperationException("pcap_setbuff() failed");
- }
- }
- }
-
- /// <value>
- /// Set the MinToCopy value in bytes
- /// WinPcap extension
- /// </value>
- public int MinToCopy
- {
- set
- {
- ThrowIfNotWinPcap();
- ThrowIfNotOpen("Can't set MinToCopy size, the device is not opened");
-
- int retval = SafeNativeMethods.pcap_setmintocopy(this.m_pcapAdapterHandle,
- value);
- if (retval != 0)
- {
- throw new System.InvalidOperationException("pcap_setbuff() failed");
- }
- }
- }
- }
-}
232 SharpPcap/LivePcapDeviceList.cs
View
@@ -1,232 +0,0 @@
-/*
-This file is part of SharpPcap.
-
-SharpPcap is free software: you can redistribute it and/or modify
-it under the terms of the GNU Lesser General Public License as published by
-the Free Software Foundation, either version 3 of the License, or
-(at your option) any later version.
-
-SharpPcap is distributed in the hope that it will be useful,
-but WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-GNU Lesser General Public License for more details.
-
-You should have received a copy of the GNU Lesser General Public License
-along with SharpPcap. If not, see <http://www.gnu.org/licenses/>.
-*/
-/*
- * Copyright 2005 Tamir Gal <tamir@tamirgal.com>
- * Copyright 2008-2009 Chris Morgan <chmorgan@gmail.com>
- */
-
-using System;
-using System.Text;
-using System.Collections.Generic;
-using System.Collections.ObjectModel;
-using System.Net.NetworkInformation;
-using System.Runtime.InteropServices;
-
-namespace SharpPcap
-{
- /// <summary>
- /// List of available Pcap Interfaces.
- /// </summary>
- public class LivePcapDeviceList : ReadOnlyCollection<LivePcapDevice>
- {
- private static LivePcapDeviceList instance;
-
- /// <summary>
- /// Method to retrieve this classes singleton instance
- /// </summary>
- public static LivePcapDeviceList Instance
- {
- get
- {
- if(instance == null)
- {
- instance = new LivePcapDeviceList();
- }
-
- return instance;
- }
- }
-
- /// <summary>
- /// Caution: Use the singlton instance unless you know why you need to call this.
- /// One use is for multiple filters on the same physical device. To apply multiple
- /// filters open the same physical device multiple times, one for each
- /// filter by calling this routine and picking the same device out of each list.
- /// </summary>
- /// <returns>
- /// A <see cref="LivePcapDeviceList"/>
- /// </returns>
- public static LivePcapDeviceList New()
- {
- return new LivePcapDeviceList();
- }
-
- /// <summary>
- /// Represents a strongly typed, read-only list of PcapDevices.
- /// </summary>
- private LivePcapDeviceList() : base(new List<LivePcapDevice>())
- {
- Refresh();
- }
-
- /// <summary>
- /// Retrieve a list of the current PcapDevices
- /// </summary>
- /// <returns>
- /// A <see cref="List&lt;LivePcapDevice&gt;"/>
- /// </returns>
- private static List<LivePcapDevice> GetDevices()
- {
- var deviceList = new List<LivePcapDevice>();
-
- var devicePtr = IntPtr.Zero;
- var errorBuffer = new StringBuilder(256);
-
- int result = SafeNativeMethods.pcap_findalldevs(ref devicePtr, errorBuffer);
- if (result < 0)
- throw new PcapException(errorBuffer.ToString());
-
- IntPtr nextDevPtr = devicePtr;
-
- while (nextDevPtr != IntPtr.Zero)
- {
- // Marshal pointer into a struct
- PcapUnmanagedStructures.pcap_if pcap_if_unmanaged =
- (PcapUnmanagedStructures.pcap_if)Marshal.PtrToStructure(nextDevPtr,
- typeof(PcapUnmanagedStructures.pcap_if));
- PcapInterface pcap_if = new PcapInterface(pcap_if_unmanaged);
- deviceList.Add(new LivePcapDevice(pcap_if));
- nextDevPtr = pcap_if_unmanaged.Next;
- }
- SafeNativeMethods.pcap_freealldevs(devicePtr); // Free unmanaged memory allocation.
-
- // go through the network interfaces to populate the mac address
- // for each of the devices
- NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
- foreach(LivePcapDevice device in deviceList)
- {
- foreach(NetworkInterface adapter in nics)
- {
- // if the name and id match then we have found the NetworkInterface
- // that matches the PcapDevice
- if(device.Name.EndsWith(adapter.Id))
- {
- var ipProperties = adapter.GetIPProperties();
- if (ipProperties.GatewayAddresses.Count != 0)
- {
- device.Interface.GatewayAddress = ipProperties.GatewayAddresses[0].Address;
- }
-
- device.Interface.MacAddress = adapter.GetPhysicalAddress();
- device.Interface.FriendlyName = adapter.Name;
- }
- }
- }
-
- return deviceList;
- }
-
- /// <summary>
- /// Refresh the device list
- /// </summary>
- public void Refresh()
- {
- lock(this)
- {
- // retrieve the current device list
- var newDeviceList = GetDevices();
-
- // update existing devices with values in the new list
- foreach(var newItem in newDeviceList)
- {
- foreach(var existingItem in base.Items)
- {
- if(newItem.Name == existingItem.Name)
- {
- // copy the flags and addresses over
- existingItem.Interface.Flags = newItem.Interface.Flags;
- existingItem.Interface.Addresses = newItem.Interface.Addresses;
-
- break; // break out of the foreach(existingItem)
- }
- }
- }
-
- // find items the current list is missing
- foreach(var newItem in newDeviceList)
- {
- bool found = false;
- foreach(var existingItem in base.Items)
- {
- if(existingItem.Name == newItem.Name)
- {
- found = true;
- break;
- }
- }
-
- // add items that we were missing
- if(!found)
- {
- base.Items.Add(newItem);
- }
- }
-
- // find items that we have that the current list is missing
- var itemsToRemove = new List<LivePcapDevice>();
- foreach(var existingItem in base.Items)
- {
- bool found = false;
-
- foreach(var newItem in newDeviceList)
- {
- if(existingItem.Name == newItem.Name)
- {
- found = true;
- break;
- }
- }
-
- // add the PcapDevice we didn't see in the new list
- if(!found)
- {
- itemsToRemove.Add(existingItem);
- }
- }
-
- // remove the items outside of the foreach() to avoid
- // enumeration errors
- foreach(var itemToRemove in itemsToRemove)
- {
- base.Items.Remove(itemToRemove);
- }
- }
- }
-
- #region PcapDevice Indexers
- /// <param name="Name">The name or description of the pcap interface to get.</param>
- public LivePcapDevice this[string Name]
- {
- get
- {
- // lock to prevent issues with multi-threaded access
- // with other methods
- lock(this)
- {
- var devices = (List<LivePcapDevice>)base.Items;
- var dev = devices.Find(delegate(LivePcapDevice i) { return i.Name == Name; });
- var result = dev ?? devices.Find(delegate(LivePcapDevice i) { return i.Description == Name; });
-
- if (result == null)
- throw new IndexOutOfRangeException();
- return result;
- }
- }
- }
- #endregion
- }
-}
125 SharpPcap/OfflinePcapDevice.cs
View
@@ -1,125 +0,0 @@
-/*
-This file is part of SharpPcap.
-
-SharpPcap is free software: you can redistribute it and/or modify
-it under the terms of the GNU Lesser General Public License as published by
-the Free Software Foundation, either version 3 of the License, or
-(at your option) any later version.
-
-SharpPcap is distributed in the hope that it will be useful,
-but WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-GNU Lesser General Public License for more details.
-
-You should have received a copy of the GNU Lesser General Public License
-along with SharpPcap. If not, see <http://www.gnu.org/licenses/>.
-*/
-/*
- * Copyright 2005 Tamir Gal <tamir@tamirgal.com>
- * Copyright 2008-2009 Chris Morgan <chmorgan@gmail.com>
- * Copyright 2008-2009 Phillip Lemon <lucidcomms@gmail.com>
- */
-
-using System;
-using System.IO;
-using System.Text;
-
-namespace SharpPcap
-{
- /// <summary>
- /// Capture packets from an offline pcap file
- /// </summary>
- public class OfflinePcapDevice : PcapDevice
- {
- private string m_pcapFile;
-
- /// <summary>
- /// The description of this device
- /// </summary>
- private const string PCAP_OFFLINE_DESCRIPTION
- = "Offline pcap file";
-
- /// <summary>
- /// Constructs a new offline device for reading
- /// pcap files
- /// </summary>
- /// <param name="pcapFile"></param>
- public OfflinePcapDevice(string pcapFile)
- {
- m_pcapFile = pcapFile;
- }
-
- /// <value>
- /// The name of the capture file
- /// </value>
- public override string Name
- {
- get
- {
- return m_pcapFile;
- }
- }
-
- /// <value>
- /// Description of the device
- /// </value>
- public override string Description
- {
- get
- {
- return PCAP_OFFLINE_DESCRIPTION;
- }
- }
-
- /// <value>
- /// Number of bytes in the capture file
- /// </value>
- public long FileSize
- {
- get
- {
- return new FileInfo( Name ).Length;
- }
- }
-
- /// <summary>
- /// The underlying pcap file name
- /// </summary>
- public string FileName
- {
- get { return System.IO.Path.GetFileName( this.Name ); }
- }
-
- /// <summary>
- /// Opens the device for capture
- /// </summary>
- public override void Open()
- {
- // holds errors
- StringBuilder errbuf = new StringBuilder( Pcap.PCAP_ERRBUF_SIZE ); //will hold errors
- // opens offline pcap file
- IntPtr adapterHandle = SafeNativeMethods.pcap_open_offline( this.Name, errbuf);
-
- // handle error
- if ( adapterHandle == IntPtr.Zero)
- {
- string err = "Unable to open offline adapter: " + errbuf.ToString();
- throw new PcapException( err );
- }
-
- // set the local handle
- this.PcapHandle = adapterHandle;
- }
-
- /// <summary>
- /// Retrieves pcap statistics
- /// </summary>
- /// <returns>
- /// A <see cref="PcapStatistics"/>
- /// </returns>
- public override PcapStatistics Statistics()
- {
- throw new NotSupportedOnOfflineDeviceException("Statistics not supported on offline device");
- }
- }
-}
92 SharpPcap/PcapAddress.cs
View
@@ -1,92 +0,0 @@
-/*
-This file is part of SharpPcap.
-
-SharpPcap is free software: you can redistribute it and/or modify
-it under the terms of the GNU Lesser General Public License as published by
-the Free Software Foundation, either version 3 of the License, or
-(at your option) any later version.
-
-SharpPcap is distributed in the hope that it will be useful,
-but WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-GNU Lesser General Public License for more details.
-
-You should have received a copy of the GNU Lesser General Public License
-along with SharpPcap. If not, see <http://www.gnu.org/licenses/>.
-*/
-/*
- * Copyright 2005 Tamir Gal <tamir@tamirgal.com>
- * Copyright 2009 Chris Morgan <chmorgan@gmail.com>
- */
-
-using System;
-using System.Text;
-
-namespace SharpPcap
-{
- /// <summary>
- /// Managed representation of the unmanaged pcap_addr structure
- /// </summary>
- public class PcapAddress
- {
- /// <summary>
- /// The address value of this PcapAddress, null if none is present
- /// </summary>
- public Sockaddr Addr { get; internal set; }
-
- /// <summary>
- /// Netmask of this PcapAddress, null if none is present
- /// </summary>
- public Sockaddr Netmask { get; internal set; }
-
- /// <summary>
- /// Broadcast address of this PcapAddress, null if none is present
- /// </summary>
- public Sockaddr Broadaddr { get; internal set; }
-
- /// <summary>
- /// Destination address, null if the interface isn't a point-to-point interface
- /// </summary>
- public Sockaddr Dstaddr {get; internal set; }
-
- internal PcapAddress()
- { }
-
- internal PcapAddress(PcapUnmanagedStructures.pcap_addr pcap_addr)
- {
- if(pcap_addr.Addr != IntPtr.Zero)
- Addr = new Sockaddr( pcap_addr.Addr );
- if(pcap_addr.Netmask != IntPtr.Zero)
- Netmask = new Sockaddr( pcap_addr.Netmask );
- if(pcap_addr.Broadaddr !=IntPtr.Zero)
- Broadaddr = new Sockaddr( pcap_addr.Broadaddr );
- if(pcap_addr.Dstaddr != IntPtr.Zero)
- Dstaddr = new Sockaddr( pcap_addr.Dstaddr );
- }
-
- /// <summary>
- /// ToString override
- /// </summary>
- /// <returns>
- /// A <see cref="System.String"/>
- /// </returns>
- public override string ToString()
- {
- StringBuilder sb = new StringBuilder();
-
- if(Addr != null)
- sb.AppendFormat("Addr: {0}\n", Addr.ToString());
-
- if(Netmask != null)
- sb.AppendFormat("Netmask: {0}\n", Netmask.ToString());
-
- if(Broadaddr != null)
- sb.AppendFormat("Broadaddr: {0}\n", Broadaddr.ToString());
-
- if(Dstaddr != null)
- sb.AppendFormat("Dstaddr: {0}\n", Dstaddr.ToString());
-
- return sb.ToString();
- }
- }
-}
622 SharpPcap/PcapDevice.cs
View
@@ -1,622 +0,0 @@
-/*
-This file is part of SharpPcap.
-
-SharpPcap is free software: you can redistribute it and/or modify
-it under the terms of the GNU Lesser General Public License as published by
-the Free Software Foundation, either version 3 of the License, or
-(at your option) any later version.
-
-SharpPcap is distributed in the hope that it will be useful,
-but WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-GNU Lesser General Public License for more details.
-
-You should have received a copy of the GNU Lesser General Public License
-along with SharpPcap. If not, see <http://www.gnu.org/licenses/>.
-*/
-/*
- * Copyright 2010 Chris Morgan <chmorgan@gmail.com>
- */
-
-using System;
-using System.Runtime.InteropServices;
-using System.Diagnostics;
-
-namespace SharpPcap
-{
- /// <summary>
- /// Base class for all pcap devices
- /// </summary>
- public abstract partial class PcapDevice
- {
- /// <summary>
- /// Low level interface object that contains device specific information
- /// </summary>
- protected PcapInterface m_pcapIf;
-
- /// <summary>
- /// Handle to an open dump file, not equal to IntPtr.Zero if a dump file is open
- /// </summary>
- protected IntPtr m_pcapDumpHandle = IntPtr.Zero;
-
- /// <summary>
- /// Handle to a pcap adapter, not equal to IntPtr.Zero if an adapter is open
- /// </summary>
- protected IntPtr m_pcapAdapterHandle = IntPtr.Zero;
-
- /// <summary>
- /// Number of packets that this adapter should capture
- /// </summary>
- protected int m_pcapPacketCount = Pcap.InfinitePacketCount;
-
- private CaptureMode m_pcapMode = CaptureMode.Packets;
- private int m_mask = 0; //for filter expression
-
- /// <summary>
- /// Fires whenever a new packet is processed, either when the packet arrives
- /// from the network device or when the packet is read from the on-disk file.<br/>
- /// For network captured packets this event is invoked only when working in "PcapMode.Capture" mode.
- /// </summary>
- public event PacketArrivalEventHandler OnPacketArrival;
-
- /// <summary>
- /// Fires whenever a new pcap statistics is available for this Pcap Device.<br/>
- /// For network captured packets this event is invoked only when working in "PcapMode.Statistics" mode.
- /// </summary>
- public event StatisticsModeEventHandler OnPcapStatistics;
-
- /// <summary>
- /// Fired when the capture process of this pcap device is stopped
- /// </summary>
- public event CaptureStoppedEventHandler OnCaptureStopped;
-
- /// <value>
- /// Low level pcap device values
- /// </value>
- public PcapInterface Interface
- {
- get { return m_pcapIf; }
- }
-
- /// <summary>
- /// Return a value indicating if this adapter is opened
- /// </summary>
- public virtual bool Opened
- {
- get{ return (PcapHandle != IntPtr.Zero); }
- }
-
- /// <summary>
- /// Gets a value indicating wether pcap dump file is already associated with this device
- /// </summary>
- public virtual bool DumpOpened
- {
- get { return m_pcapDumpHandle!=IntPtr.Zero; }
- }
-
- /// <summary>
- /// Gets the name of the device
- /// </summary>
- public abstract string Name
- {
- get;
- }
-
- /// <value>
- /// Description of the device
- /// </value>
- public abstract string Description
- {
- get;
- }
-
- /// <summary>
- /// Return the pcap link layer value of an adapter.
- /// </summary>
- public virtual PacketDotNet.LinkLayers PcapDataLink
- {
- get
- {
- ThrowIfNotOpen("Cannot get datalink, the pcap device is not opened");
- return (PacketDotNet.LinkLayers)SafeNativeMethods.pcap_datalink(PcapHandle);
- }
- }
-
- /// <value>
- /// WinPcap specific property
- /// </value>
- public virtual CaptureMode Mode
- {
- get
- {
- return m_pcapMode;
- }
-
- set
- {
- ThrowIfNotWinPcap();
- ThrowIfNotOpen("Mode");
-
- m_pcapMode = value;
- int result = SafeNativeMethods.pcap_setmode(this.PcapHandle , (int)m_pcapMode);
- if (result < 0)
- throw new PcapException("Error setting PcapDevice mode. : " + LastError);
- }
- }
-
- /// <summary>
- /// The underlying pcap device handle
- /// </summary>
- internal virtual IntPtr PcapHandle
- {
- get { return m_pcapAdapterHandle; }
- set { m_pcapAdapterHandle = value; }
- }
-
- /// <summary>
- /// Retrieve the last error string for a given pcap_t* device
- /// </summary>
- /// <param name="deviceHandle">
- /// A <see cref="IntPtr"/>
- /// </param>
- /// <returns>
- /// A <see cref="System.String"/>
- /// </returns>
- internal static string GetLastError(IntPtr deviceHandle)
- {
- IntPtr err_ptr = SafeNativeMethods.pcap_geterr(deviceHandle);
- return Marshal.PtrToStringAnsi(err_ptr);
- }
-
- /// <summary>
- /// The last pcap error associated with this pcap device
- /// </summary>
- public string LastError
- {
- get { return GetLastError(PcapHandle); }
- }
-
- /// <summary>
- /// Open the device with class specific options
- /// </summary>
- public abstract void Open();
-
- /// <summary>
- /// Closes this adapter
- /// </summary>
- public virtual void Close()
- {
- if(PcapHandle==IntPtr.Zero)
- return;
-
- if (Started)
- {
- StopCapture();
- }
- SafeNativeMethods.pcap_close(PcapHandle);
- PcapHandle = IntPtr.Zero;
-
- //Remove event handlers
- if ( OnPacketArrival != null)
- {
- foreach(PacketArrivalEventHandler pa in OnPacketArrival.GetInvocationList())
- {
- OnPacketArrival -= pa;
- }
- }
- if ( OnPcapStatistics != null)
- {
- foreach(StatisticsModeEventHandler pse in OnPcapStatistics.GetInvocationList())
- {
- OnPcapStatistics -= pse;
- }
- }
- }
-
- /// <summary>
- /// Retrieves pcap statistics
- /// </summary>
- /// <returns>
- /// A <see cref="PcapStatistics"/>
- /// </returns>
- public abstract PcapStatistics Statistics();
-
- /// <summary>
- /// Notify the OnPacketArrival delegates about a newly captured packet
- /// </summary>
- /// <param name="p">
- /// A <see cref="PacketDotNet.RawPacket"/>
- /// </param>
- private void SendPacketArrivalEvent(PacketDotNet.RawPacket p)
- {
- if(Mode == CaptureMode.Packets)
- {
- var handler = OnPacketArrival;
- if(handler != null )
- {
- //Invoke the packet arrival event
- handler(this, new CaptureEventArgs(p, this));
- }
- }
- else if(Mode == CaptureMode.Statistics)
- {
- var handler = OnPcapStatistics;
- if(handler != null)
- {
- //Invoke the pcap statistics event
- handler(this, new StatisticsModeEventArgs(p, this));
- }
- }
- }
-
- /// <summary>
- /// Notify the delegates that are subscribed to the capture stopped event
- /// </summary>
- /// <param name="status">
- /// A <see cref="CaptureStoppedEventStatus"/>
- /// </param>
- private void SendCaptureStoppedEvent(CaptureStoppedEventStatus status)
- {
- var handler = OnCaptureStopped;
- if(handler != null)
- {
- handler(this, status);
- }
- }
-
- /// <summary>
- /// Gets the next packet captured on this device
- /// </summary>
- /// <returns>The next packet captured on this device</returns>
- public virtual PacketDotNet.RawPacket GetNextPacket()
- {
- PacketDotNet.RawPacket p;
- int res = GetNextPacket( out p );
- if(res==-1)
- throw new PcapException("Error receiving packet.");
- return p;
- }
-
- /// <summary>
- /// Gets the next packet captured on this device
- /// </summary>
- /// <param name="p">A packet reference</param>
- /// <returns>A reference to a packet object</returns>
- public virtual int GetNextPacket(out PacketDotNet.RawPacket p)
- {
- //Pointer to a packet info struct
- IntPtr header = IntPtr.Zero;
-
- //Pointer to a packet struct
- IntPtr data = IntPtr.Zero;
- int res = 0;
-
- // using an invalid PcapHandle can result in an unmanaged segfault
- // so check for that here
- ThrowIfNotOpen("Device must be opened via Open() prior to use");
-
- //Get a packet from winpcap
- res = SafeNativeMethods.pcap_next_ex( PcapHandle, ref header, ref data);
- p = null;
-
- if(res>0)
- {
- //Marshal the packet
- if ( (header != IntPtr.Zero) && (data != IntPtr.Zero) )
- {
- p = MarshalRawPacket(header, data);
- }
- }
- return res;
- }
-
- /// <summary>
- /// Pcap_loop callback method.
- /// </summary>
- protected virtual void PacketHandler(IntPtr param, IntPtr /* pcap_pkthdr* */ header, IntPtr data)
- {
- var p = MarshalRawPacket(header, data);
- SendPacketArrivalEvent(p);
- }
-
- /// <summary>
- /// Convert an unmanaged packet into a managed PacketDotNet.RawPacket
- /// </summary>
- /// <param name="header">
- /// A <see cref="IntPtr"/>
- /// </param>
- /// <param name="data">
- /// A <see cref="IntPtr"/>
- /// </param>
- /// <returns>
- /// A <see cref="PacketDotNet.RawPacket"/>
- /// </returns>
- protected virtual PacketDotNet.RawPacket MarshalRawPacket(IntPtr /* pcap_pkthdr* */ header, IntPtr data)
- {
- PacketDotNet.RawPacket p;
-
- // marshal the header
- var pcapHeader = new PcapHeader(header);
-
- var pkt_data = new byte[pcapHeader.CaptureLength];
- Marshal.Copy(data, pkt_data, 0, (int)pcapHeader.CaptureLength);
-
- p = new PacketDotNet.RawPacket(PcapDataLink,
- new PacketDotNet.PosixTimeval(pcapHeader.Seconds,
- pcapHeader.MicroSeconds),
- pkt_data);
-
- return p;
- }
-
- #region Dump methods
- /// <summary>
- /// Opens a file for packet writings
- /// </summary>
- /// <param name="fileName"></param>
- public void DumpOpen(string fileName)
- {
- ThrowIfNotOpen("Dump requires an open device");
-
- if(DumpOpened)
- {
- throw new PcapException("A dump file is already opened");
- }
- m_pcapDumpHandle = SafeNativeMethods.pcap_dump_open(PcapHandle, fileName);
- if(!DumpOpened)
- throw new PcapException("Error openning dump file.");
- }
-
- /// <summary>
- /// Closes the opened dump file
- /// </summary>
- public void DumpClose()
- {
- if(DumpOpened)
- {
- SafeNativeMethods.pcap_dump_close(m_pcapDumpHandle);
- m_pcapDumpHandle = IntPtr.Zero;
- }
- }
-
- /// <summary>
- /// Flushes all write buffers of the opened dump file
- /// </summary>
- public void DumpFlush()
- {
- if (DumpOpened)
- {
- int result = SafeNativeMethods.pcap_dump_flush(m_pcapDumpHandle);
- if (result < 0)
- throw new PcapException("Error writing buffer to dumpfile. " + LastError);
- }
- }
-
- /// <summary>
- /// Writes a packet to the pcap dump file associated with this device.
- /// </summary>
- public void Dump(byte[] p, PcapHeader h)
- {
- ThrowIfNotOpen("Cannot dump packet, device is not opened");
- if(!DumpOpened)
- throw new DeviceNotReadyException("Cannot dump packet, dump file is not opened");
-
- //Marshal packet
- IntPtr pktPtr;
- pktPtr = Marshal.AllocHGlobal(p.Length);
- Marshal.Copy(p, 0, pktPtr, p.Length);
-
- //Marshal header
- IntPtr hdrPtr = h.MarshalToIntPtr();
-
- SafeNativeMethods.pcap_dump(m_pcapDumpHandle, hdrPtr, pktPtr);
-
- Marshal.FreeHGlobal(pktPtr);
- Marshal.FreeHGlobal(hdrPtr);
- }
-
- /// <summary>
- /// Writes a packet to the pcap dump file associated with this device.
- /// </summary>
- /// <param name="p">The packet to write</param>
- public void Dump(byte[] p)
- {
- Dump(p, new PcapHeader(0, 0, (uint)p.Length, (uint)p.Length));
- }
-
- /// <summary>
- /// Writes a packet to the pcap dump file associated with this device.
- /// </summary>
- /// <param name="p">The packet to write</param>
- public void Dump(PacketDotNet.RawPacket p)
- {
- var data = p.Data;
- var timeval = p.Timeval;
- var header = new PcapHeader(timeval.Seconds, timeval.MicroSeconds,
- (uint)data.Length, (uint)data.Length);
- Dump(data, header);
- }
-
- #endregion
-
- #region Filtering
- /// <summary>
- /// Deprecated: Use the Filter property instead. This api will be removed in
- /// the next release
- /// </summary>
- /// <param name="filterExpression">The filter expression to compile</param>
- public void SetFilter(string filterExpression)
- {
- // save the filter string
- _filterString = filterExpression;
-
- int res;
- IntPtr bpfProgram;
- string errorString;
-
- // pcap_setfilter() requires a valid pcap_t which isn't present if
- // the device hasn't been opened
- ThrowIfNotOpen("device is not open");
-
- // attempt to compile the program
- if(!CompileFilter(PcapHandle, filterExpression, (uint)m_mask, out bpfProgram, out errorString))
- {
- string err = string.Format("Can't compile filter ({0}) : {1} ", filterExpression, errorString);
- throw new PcapException(err);
- }
-
- //associate the filter with this device
- res = SafeNativeMethods.pcap_setfilter( PcapHandle, bpfProgram );
-
- // Free the program whether or not we were successful in setting the filter
- // we don't want to leak unmanaged memory if we throw an exception.
- FreeBpfProgram(bpfProgram);
-
- //watch for errors
- if(res < 0)
- {
- errorString = string.Format("Can't set filter ({0}) : {1}", filterExpression, LastError);
- throw new PcapException(errorString);
- }
- }
-
- private string _filterString;
-
- /// <summary>
- /// Kernel level filtering expression associated with this device.
- /// For more info on filter expression syntax, see:
- /// http://www.winpcap.org/docs/docs31/html/group__language.html
- /// </summary>
- public virtual string Filter
- {
- get
- {
- return _filterString;
- }
-
- set
- {
- SetFilter(_filterString);
- }
- }
-
- // If CompileFilter() returns true bpfProgram must be freed by passing it to FreeBpfProgram()
- /// or unmanaged memory will be leaked
- private static bool CompileFilter(IntPtr pcapHandle,
- string filterExpression,
- uint mask,
- out IntPtr bpfProgram,
- out string errorString)
- {
- int result;
- string err = String.Empty;
-
- bpfProgram = IntPtr.Zero;
- errorString = null;
-
- //Alocate an unmanaged buffer
- bpfProgram = Marshal.AllocHGlobal( Marshal.SizeOf(typeof(PcapUnmanagedStructures.bpf_program)));
-
- //compile the expressions
- result = SafeNativeMethods.pcap_compile(pcapHandle,
- bpfProgram,
- filterExpression,
- 1,
- mask);
-
- if(result < 0)
- {
- err = GetLastError(pcapHandle);
-
- // free up the program memory
- Marshal.FreeHGlobal(bpfProgram);
- bpfProgram = IntPtr.Zero; // make sure not to pass out a valid pointer
-
- // set the error string
- errorString = err;
-
- return false;
- }
-
- return true;
- }
-
- /// <summary>
- /// Free memory allocated in CompileFilter()
- /// </summary>
- /// <param name="bpfProgram">
- /// A <see cref="IntPtr"/>
- /// </param>
- private static void FreeBpfProgram(IntPtr bpfProgram)
- {
- // free any pcap internally allocated memory from pcap_compile()
- SafeNativeMethods.pcap_freecode(bpfProgram);
-
- // free allocated buffers
- Marshal.FreeHGlobal(bpfProgram);
- }
-
- /// <summary>
- /// Returns true if the filter expression was able to be compiled into a
- /// program without errors
- /// </summary>
- public static bool CheckFilter(string filterExpression,
- out string errorString)
- {
- IntPtr bpfProgram;
- IntPtr fakePcap = SafeNativeMethods.pcap_open_dead((int)PacketDotNet.LinkLayers.Ethernet, Pcap.MAX_PACKET_SIZE);
-
- uint mask = 0;
- if(!CompileFilter(fakePcap, filterExpression, mask, out bpfProgram, out errorString))
- {
- SafeNativeMethods.pcap_close(fakePcap);
- return false;
- }
-
- FreeBpfProgram(bpfProgram);
-
- SafeNativeMethods.pcap_close(fakePcap);
- return true;
- }
- #endregion
-
- /// <summary>
- /// Helper method for ensuring we are running in winpcap. Throws
- /// a PcapWinPcapRequiredException() if not on a windows platform
- /// </summary>
- internal static void ThrowIfNotWinPcap()
- {
- if((Environment.OSVersion.Platform != PlatformID.Win32NT) &&
- (Environment.OSVersion.Platform != PlatformID.Win32Windows))
- {
- throw new WinPcapRequiredException("only supported in winpcap");
- }
- }
-
- /// <summary>
- /// Helper method for checking that the adapter is open, throws an
- /// exception with a string of ExceptionString if the device isn't open
- /// </summary>
- /// <param name="ExceptionString">
- /// A <see cref="System.String"/>
- /// </param>
- protected void ThrowIfNotOpen(string ExceptionString)
- {
- if(!Opened)
- {
- throw new DeviceNotReadyException(ExceptionString);
- }
- }
-
- /// <summary>
- /// Override the default ToString() implementation
- /// </summary>
- /// <returns>
- /// A <see cref="System.String"/>
- /// </returns>
- public override string ToString ()
- {
- return "interface: " + m_pcapIf.ToString() + "\n";
- }
- }
-}
399 SharpPcap/PcapDeviceCaptureLoop.cs
View
@@ -1,399 +0,0 @@
-// Define that lets us test behavior using Mono.Unix.Native directly avoiding
-// reflection. Useful for debugging but we don't want to ship an assembly that
-// depends on Mono.Unix.Native because many users are on MS .Net which lacks this
-// assembly
-//#define UseMonoUnixNativeDirectly
-
-/*
-This file is part of SharpPcap.
-
-SharpPcap is free software: you can redistribute it and/or modify
-it under the terms of the GNU Lesser General Public License as published by
-the Free Software Foundation, either version 3 of the License, or
-(at your option) any later version.
-
-SharpPcap is distributed in the hope that it will be useful,
-but WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-GNU Lesser General Public License for more details.
-
-You should have received a copy of the GNU Lesser General Public License
-along with SharpPcap. If not, see <http://www.gnu.org/licenses/>.
-*/
-/*
- * Copyright 2005 Tamir Gal <tamir@tamirgal.com>
- * Copyright 2008-2010 Chris Morgan <chmorgan@gmail.com>
- * Copyright 2008-2009 Phillip Lemon <lucidcomms@gmail.com>
- */
-
-using System;
-using System.Threading;
-using System.Reflection;
-#if UseMonoUnixNativeDirectly
-using Mono.Unix.Native;
-#endif
-
-// NOTE: The reflection code in here may seem complex but it serves an important
-// purpose.
-//
-// Under Unix, pcap_loop(), pcap_dispatch(), pcap_next() and pcap_next_ex()
-// all perform blocking read() calls at the os level that have NO timeout.
-// If the user wishes to stop capturing on an adapter they will need to wait
-// until the next packet arrives for the capture loop to wake up and look to see
-// if it has been asked to shut down. This may be never in the case of inactive
-// adapters or far longer than what the user desires.
-//
-// So, to avoid the issue we use reflection to load up Mono.Posix and invoke
-// the poll() system call. The thread sleeps on the poll() and only when woken
-// up and indicating that data is available do we call one of the pcap
-// data retrieval routines. This is how we avoid blocking for long periods
-// or forever.
-//
-// Poll enables us to set a timeout. The timeout is chosen to be long
-// enough to avoid a noticable performance impact from frequent looping
-// but short enough to satisify the timing constraints of the Thread.Join() in
-// the stop capture code.
-//
-
-namespace SharpPcap
-{
- public partial class PcapDevice
- {
- private Thread captureThread;
- private bool shouldCaptureThreadStop;
-
- /// <summary>
- /// If Environment.OSVersion.Platform is unix and MonoUnixFound is true
- /// then we can support proper termination of the capture loop
- /// </summary>
- /// <returns>
- /// A <see cref="System.Boolean"/>
- /// </returns>
- private static bool MonoUnixFound = false;
-
- // if true then we are running under a unix platform so we must be using libpcap
- private static bool isLibPcap = (Environment.OSVersion.Platform == PlatformID.Unix);
-
-#if !UseMonoUnixNativeDirectly
- // variables for unix dynamic invocation of Mono.Unix.Native.Syscall.poll()
- private static Assembly MonoUnixNativeAssembly;
- private static Type SyscallType;
- private static Type PollfdType;
- private static Type PollEventsType;
-
- // values of the PollEvents.POLLPRI and POLLIN enum
- private static short POLLPRI;
- private static short POLLIN;
-
- /// <summary>
- /// Setup the reflection type and methodinfo for invocation of
- /// Mono.Unix.Native.Syscall.poll() to avoid timeouts when
- /// stopping the capture thread
- /// </summary>
- private static bool UnixSetupMonoUnixNative()
- {
- // load the assemly
- var AssemblyName = "Mono.Posix, Version=2.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756";
-
- try
- {
- MonoUnixNativeAssembly = Assembly.Load(AssemblyName);
- } catch(System.Exception)
- {
- // unable to load the Mono.Posix assembly so we can't
- // avoid blocking forever in the capture loop
- return false;
- }
-
- SyscallType = MonoUnixNativeAssembly.GetType("Mono.Unix.Native.Syscall");
- if(SyscallType == null)
- {
- throw new System.InvalidOperationException("SyscallType is null");
- }
-
- PollfdType = MonoUnixNativeAssembly.GetType("Mono.Unix.Native.Pollfd");
- if(PollfdType == null)
- {
- throw new System.InvalidOperationException("PollfdType is null");
- }
-
- PollEventsType = MonoUnixNativeAssembly.GetType("Mono.Unix.Native.PollEvents");
- if(PollEventsType == null)
- {
- throw new System.InvalidOperationException("PollEventsType is null");
- }
-
- // retrieve the pollpri and pollin values
- FieldInfo field;
- field = PollEventsType.GetField("POLLPRI");
- POLLPRI = (short)field.GetValue(PollEventsType);
-
- field = PollEventsType.GetField("POLLIN");
- POLLIN = (short)field.GetRawConstantValue();
-
- return true;
- }
-
- static PcapDevice()
- {
- // if we are running under libpcap and mono then we should
- // setup the Mono.Unix.Native methods
- if(Environment.OSVersion.Platform == PlatformID.Unix)
- {
- MonoUnixFound = UnixSetupMonoUnixNative();
- }
- }
-#endif
-
- /// <summary>
- /// Return a value indicating if the capturing process of this adapter is started
- /// </summary>
- public virtual bool Started
- {
- get { return (captureThread != null); }
- }
-
- // time we give the capture thread to stop before we assume that
- // there is an error
- private TimeSpan stopCaptureTimeout = new TimeSpan(0, 0, 1);
-
- /// <summary>
- /// Maximum time within which the capture thread must join the main thread (on
- /// <see cref="StopCapture"/>) or else the thread is aborted and an exception thrown.
- /// </summary>
- public TimeSpan StopCaptureTimeout
- {
- get { return stopCaptureTimeout; }
- set { stopCaptureTimeout = value; }
- }
-
- /// <summary>
- /// Starts the capturing process
- /// </summary>
- public virtual void StartCapture()
- {
- if (!Started)
- {
- if (!Opened)
- throw new DeviceNotReadyException("Can't start capture, the pcap device is not opened.");
-
- shouldCaptureThreadStop = false;
- captureThread = new Thread(new ThreadStart(this.CaptureThread));
- captureThread.Start();
- }
- }
-
- /// <summary>
- /// Stops the capture process
- ///
- /// Throws an exception if the stop capture timeout is exceeded and the
- /// capture thread was aborted
- /// </summary>
- public virtual void StopCapture()
- {
- if (Started)
- {
- shouldCaptureThreadStop = true;
- if(!captureThread.Join(StopCaptureTimeout))
- {
- captureThread.Abort();
- captureThread = null;
- string error;
-
- if(isLibPcap && !MonoUnixFound)
- {
- error = string.Format("captureThread was aborted after {0}. Using a Mono" +
- " version >= 2.4 and installing Mono.Posix should" +
- " enable smooth thread shutdown",
- StopCaptureTimeout.ToString());
- } else
- {
- error = string.Format("captureThread was aborted after {0}",
- StopCaptureTimeout.ToString());
- }
-
- throw new PcapException(error);
- }
-
- captureThread = null; // otherwise we will always return true from PcapDevice.Started
- }
- }
-
- /// <summary>
- /// Synchronously capture packets on this device. Method blocks forever.
- /// </summary>
- public void Capture()
- {
- Capture(Pcap.InfinitePacketCount);
- }
-
- /// <summary>
- /// Synchronously captures packets on this network device. This method will block
- /// until capturing is finished.
- /// </summary>
- /// <param name="packetCount">The number of packets to be captured.
- /// -1 means capture indefiniately</param>
- public void Capture(int packetCount)
- {
- m_pcapPacketCount = packetCount;
- CaptureThread();
-
- // restore the capture count incase the user Starts
- m_pcapPacketCount = Pcap.InfinitePacketCount;
- }
-
- /// <summary>
- /// The capture thread
- /// </summary>
- private void CaptureThread()
- {
- if (!Opened)
- throw new DeviceNotReadyException("Capture called before PcapDevice.Open()");
-
- var usePoll = (this is LivePcapDevice) &&
- isLibPcap && MonoUnixFound;
-
- // unix specific code
- int captureFileDescriptor = 0;
- if(usePoll)
- {
- // retrieve the file descriptor of the adapter for use with poll()
- captureFileDescriptor = SafeNativeMethods.pcap_fileno(PcapHandle);
- if(captureFileDescriptor == -1)
- {
- SendCaptureStoppedEvent(CaptureStoppedEventStatus.ErrorWhileCapturing);
- return;
- }
- }
-
- SafeNativeMethods.pcap_handler Callback = new SafeNativeMethods.pcap_handler(PacketHandler);
-
- // unix specific code
-#if UseMonoUnixNativeDirectly
- Pollfd[] pollFds = new Pollfd[1];
-#else
- System.Array pollFds = null;
- object[] PollParameters = null;
-#endif
-
- // Timeout chosen to allow the capture thread to loop frequently enough
- // to enable it to properly exit when the user requests it to but
- // infrequently enough to cause any noticable performance overhead
- int millisecondTimeout = 500;
-
- if(usePoll)
- {
-#if UseMonoUnixNativeDirectly
- pollFds[0].fd = captureFileDescriptor;
- pollFds[0].events = PollEvents.POLLPRI | Mono.Unix.Native.PollEvents.POLLIN;
-#else
- FieldInfo field;
- pollFds = Array.CreateInstance(PollfdType, 1);
-
- // create a PollFd struct instance
- var pollFd = Activator.CreateInstance(PollfdType);
-
- // set the descriptor field
- field = PollfdType.GetField("fd");
- field.SetValue(pollFd, captureFileDescriptor);
-
- // set the events field
- short eventValue = (short)(POLLIN | POLLPRI); // mask the two together
- field = PollfdType.GetField("events");
- field.SetValue(pollFd, eventValue);
-
- // set the Pollfd entry
- pollFds.SetValue(pollFd, 0);
-
- // setup the parameters we will pass to the poll() method
- PollParameters = new object[2];
- PollParameters[0] = pollFds;
- PollParameters[1] = millisecondTimeout;
-#endif
- }
-
- while(!shouldCaptureThreadStop)
- {
- // unix specific code, we want to poll for packets
- // otherwise if we call pcap_dispatch() the read() will block
- // and won't resume until a packet arrives OR until a signal
- // occurs
- if(usePoll)
- {
- // block here
-#if UseMonoUnixNativeDirectly
- var result = Mono.Unix.Native.Syscall.poll(pollFds, millisecondTimeout);
-#else
- object o = SyscallType.InvokeMember("poll",
- BindingFlags.InvokeMethod,
- Type.DefaultBinder,
- null,
- PollParameters);
- int result = (int)o;
-#endif
-
- // if we have no poll results, just loop
- if(result <= 0)
- {
- continue;
- }
-
- // fall through here to the pcap_dispatch() call
- }
-
- int res = SafeNativeMethods.pcap_dispatch(PcapHandle, m_pcapPacketCount, Callback, IntPtr.Zero);
-
- // pcap_dispatch() returns the number of packets read or, a status value if the value
- // is negative
- if(res <= 0)
- {
- switch (res) // Check pcap loop status results and notify upstream.
- {
- case Pcap.LOOP_USER_TERMINATED: // User requsted loop termination with StopCapture()
- SendCaptureStoppedEvent(CaptureStoppedEventStatus.CompletedWithoutError);
- return;
- case Pcap.LOOP_COUNT_EXHAUSTED: // m_pcapPacketCount exceeded (successful exit)
- {
- // NOTE: pcap_dispatch() returns 0 when a timeout occurrs so to prevent timeouts
- // from causing premature exiting from the capture loop we only consider
- // exhausted events to cause an escape from the loop when they are from
- // offline devices, ie. files read from disk
- if(this is OfflinePcapDevice)
- {
- SendCaptureStoppedEvent(CaptureStoppedEventStatus.CompletedWithoutError);
- return;
- }
- break;
- }
- case Pcap.LOOP_EXIT_WITH_ERROR: // An error occurred whilst capturing.
- SendCaptureStoppedEvent(CaptureStoppedEventStatus.CompletedWithoutError);
- return;
- default: // This can only be triggered by a bug in libpcap.
- throw new PcapException("Unknown pcap_loop exit status.");
- }
- } else // res > 0
- {
- // if we aren't capturing infinitely we need to account for
- // the packets that we read
- if(m_pcapPacketCount != Pcap.InfinitePacketCount)
- {
- // take away for the packets read
- if(m_pcapPacketCount >= res)
- m_pcapPacketCount -= res;
- else
- m_pcapPacketCount = 0;
-
- // no more packets to capture, we are finished capturing
- if(m_pcapPacketCount == 0)
- {
- SendCaptureStoppedEvent(CaptureStoppedEventStatus.CompletedWithoutError);
- return;
- }
- }
- }
- }
-
- SendCaptureStoppedEvent(CaptureStoppedEventStatus.CompletedWithoutError);
- }
- }
-}
172 SharpPcap/PcapHeader.cs
View
@@ -1,172 +0,0 @@
-/*
-This file is part of SharpPcap.
-
-SharpPcap is free software: you can redistribute it and/or modify
-it under the terms of the GNU Lesser General Public License as published by
-the Free Software Foundation, either version 3 of the License, or
-(at your option) any later version.
-
-SharpPcap is distributed in the hope that it will be useful,
-but WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-GNU Lesser General Public License for more details.
-
-You should have received a copy of the GNU Lesser General Public License
-along with SharpPcap. If not, see <http://www.gnu.org/licenses/>.
-*/
-/*
- * Copyright 2005 Tamir Gal <tamir@tamirgal.com>
- * Copyright 2008-2009 Chris Morgan <chmorgan@gmail.com>
- */
-
-using System;
-using System.Runtime.InteropServices;
-
-namespace SharpPcap
-{
- /// <summary>
- /// A wrapper class for libpcap's pcap_pkthdr structure
- /// </summary>
- public class PcapHeader
- {
- /// <summary>
- /// Constructs a new PcapHeader
- /// </summary>
- public PcapHeader()
- {
- }
-
- internal PcapHeader (IntPtr pcap_pkthdr)
- {
- if(Environment.OSVersion.Platform == PlatformID.Unix)
- {
- var pkthdr = (PcapUnmanagedStructures.pcap_pkthdr_unix)Marshal.PtrToStructure(pcap_pkthdr,
- typeof(PcapUnmanagedStructures.pcap_pkthdr_unix));
- this.CaptureLength = pkthdr.caplen;
- this.PacketLength = pkthdr.len;
- this.Seconds = (ulong)pkthdr.ts.tv_sec;
- this.MicroSeconds = (ulong)pkthdr.ts.tv_usec;
- } else
- {
- var pkthdr = (PcapUnmanagedStructures.pcap_pkthdr_windows)Marshal.PtrToStructure(pcap_pkthdr,
- typeof(PcapUnmanagedStructures.pcap_pkthdr_windows));
- this.CaptureLength = pkthdr.caplen;
- this.PacketLength = pkthdr.len;
- this.Seconds = (ulong)pkthdr.ts.tv_sec;
- this.MicroSeconds = (ulong)pkthdr.ts.tv_usec;
- }
- }
-
- /// <summary>
- /// Constructs a new PcapHeader
- /// </summary>
- /// <param name="seconds">The seconds value of the packet's timestamp</param>
- /// <param name="microseconds">The microseconds value of the packet's timestamp</param>
- /// <param name="packetLength">The actual length of the packet</param>
- /// <param name="captureLength">The length of the capture</param>
- public PcapHeader( ulong seconds, ulong microseconds, uint packetLength, uint captureLength )
- {
- this.Seconds = seconds;
- this.MicroSeconds = microseconds;
- this.PacketLength = packetLength;
- this.CaptureLength = captureLength;
- }
-
- private ulong _seconds;
-
- /// <summary>
- /// The seconds value of the packet's timestamp
- /// </summary>
- public ulong Seconds
- {
- get { return _seconds; }
- set { _seconds = value; }
- }
-
- private ulong _usec;
-
- /// <summary>
- /// The microseconds value of the packet's timestamp
- /// </summary>
- public ulong MicroSeconds
- {
- get { return _usec; }
- set { _usec = value; }
- }
-
- private uint _packetlength;
-
- /// <summary>
- /// The actual length of the packet
- /// </summary>
- public uint PacketLength
- {
- get { return _packetlength; }
- set { _packetlength = value; }
- }
-
- private uint _capturelength;
-
- /// <summary>
- /// The length of the capture
- /// </summary>
- public uint CaptureLength
- {
- get { return _capturelength; }
- set { _capturelength = value; }
- }
-
- /// <summary>
- /// Return the DateTime value of this pcap header
- /// </summary>
- virtual public System.DateTime Date
- {
- get
- {
- DateTime time = new DateTime(1970,1,1);
- time = time.AddSeconds(Seconds);
- time = time.AddMilliseconds(MicroSeconds / 1000);
- return time.ToLocalTime();
- }
- }
-
- /// <summary>
- /// Marshal this structure into the platform dependent version and return
- /// and IntPtr to that memory
- ///
- /// NOTE: IntPtr MUST BE FREED via Marshal.FreeHGlobal()
- /// </summary>
- /// <returns>
- /// A <see cref="IntPtr"/>
- /// </returns>
- public IntPtr MarshalToIntPtr()
- {
- IntPtr hdrPtr;
-
- if(Environment.OSVersion.Platform == PlatformID.Unix)
- {
- // setup the structure to marshal
- var pkthdr = new PcapUnmanagedStructures.pcap_pkthdr_unix();
- pkthdr.caplen = this.CaptureLength;
- pkthdr.len = this.PacketLength;
- pkthdr.ts.tv_sec = (IntPtr)this.Seconds;
- pkthdr.ts.tv_usec = (IntPtr)this.MicroSeconds;
-
- hdrPtr = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(PcapUnmanagedStructures.pcap_pkthdr_unix)));
- Marshal.StructureToPtr(pkthdr, hdrPtr, true);
- } else
- {
- var pkthdr = new PcapUnmanagedStructures.pcap_pkthdr_windows();
- pkthdr.caplen = this.CaptureLength;
- pkthdr.len = this.PacketLength;
- pkthdr.ts.tv_sec = (int)this.Seconds;
- pkthdr.ts.tv_usec = (int)this.MicroSeconds;
-
- hdrPtr = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(PcapUnmanagedStructures.pcap_pkthdr_windows)));
- Marshal.StructureToPtr(pkthdr, hdrPtr, true);
- }
-
- return hdrPtr;
- }
- }
-}
182 SharpPcap/PcapInterface.cs
View
@@ -1,182 +0,0 @@
-/*
-This file is part of SharpPcap.
-
-SharpPcap is free software: you can redistribute it and/or modify
-it under the terms of the GNU Lesser General Public License as published by
-the Free Software Foundation, either version 3 of the License, or
-(at your option) any later version.
-
-SharpPcap is distributed in the hope that it will be useful,
-but WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-GNU Lesser General Public License for more details.
-
-You should have received a copy of the GNU Lesser General Public License
-along with SharpPcap. If not, see <http://www.gnu.org/licenses/>.
-*/
-/*
- * Copyright 2005 Tamir Gal <tamir@tamirgal.com>
- * Copyright 2009 Chris Morgan <chmorgan@gmail.com>
- */
-
-using System;
-using System.Collections.Generic;
-using System.Text;
-using System.Runtime.InteropServices;
-using SharpPcap;
-
-namespace SharpPcap
-{
- /// <summary>
- /// managed version of struct pcap_if
- /// NOTE: we can't use pcap_if directly because the class contains
- /// a pointer to pcap_if that will be freed when the
- /// device memory is freed, so instead convert the unmanaged structure
- /// to a managed one to avoid this issue
- /// </summary>
- public class PcapInterface
- {
- /// <value>
- /// Name of the interface. Used internally when passed to pcap_open_live()
- /// </value>
- public string Name { get; internal set; }
-
- /// <value>
- /// Human readable interface name derived from System.Net.NetworkInformation.NetworkInterface.Name
- /// </value>
- public string FriendlyName { get; internal set; }
-
- /// <value>
- /// Text description of the interface as given by pcap/winpcap
- /// </value>
- public string Description { get; internal set; }
-
- /// <value>
- /// Gateway address of this device
- /// NOTE: May only be available on Windows
- /// </value>
- public System.Net.IPAddress GatewayAddress { get; internal set; }
-
- /// <value>
- /// Addresses associated with this device
- /// </value>
- public List<PcapAddress> Addresses { get; internal set; }
-
- /// <value>
- /// Pcap interface flags
- /// </value>
- public uint Flags { get; internal set; }
-
- private PcapAddress m_macAddress;
-
- /// <summary>
- /// MacAddress of the interface
- /// </summary>
- public System.Net.NetworkInformation.PhysicalAddress MacAddress
- {
- get
- {
- return m_macAddress.Addr.hardwareAddress;
- }
-
- internal set
- {
- // do we already have a hardware address for this device?
- if(m_macAddress != null)
- {
-#if false
- Console.WriteLine("Overwriting hardware address "
- + m_macAddress.Addr.hardwareAddress.ToString()
- + " with " +
- value.ToString());
-#endif
- // overwrite the value with the new value
- m_macAddress.Addr.hardwareAddress = value;
- } else
- {
-#if false
- Console.WriteLine("Creating new PcapAddress entry for this hardware address");
-#endif
- // create a new entry for the mac address
- PcapAddress newAddress = new PcapAddress();
- newAddress.Addr = new Sockaddr(value);
-
- // add the address to our addresses list
- Addresses.Add(newAddress);
-
- // m_macAddress should point to this hardware address
- m_macAddress = newAddress;
- }
- }
- }
-
- internal PcapInterface(PcapUnmanagedStructures.pcap_if pcapIf)
- {
- Name = pcapIf.Name;
- Description = pcapIf.Description;
- Flags = pcapIf.Flags;
-
- // retrieve addresses
- Addresses = new List<PcapAddress>();
- IntPtr address = pcapIf.Addresses;
- while(address != IntPtr.Zero)
- {
- //A sockaddr struct
- PcapUnmanagedStructures.pcap_addr addr;
-
- //Marshal memory pointer into a struct
- addr = (PcapUnmanagedStructures.pcap_addr)Marshal.PtrToStructure(address,
- typeof(PcapUnmanagedStructures.pcap_addr));
-
- PcapAddress newAddress = new PcapAddress(addr);
- Addresses.Add(newAddress);
-
- // is this a hardware address?
- // if so we should set our internal m_macAddress member variable
- if((newAddress.Addr != null) &&
- (newAddress.Addr.type == Sockaddr.Type.HARDWARE))
- {
- if(m_macAddress == null)
- {
- m_macAddress = newAddress;
- } else
- {
- throw new System.InvalidOperationException("found multiple hardware addresses, existing addr "
- + MacAddress.ToString() + ", new address " + newAddress.Addr.hardwareAddress.ToString());
- }
- }
-
- address = addr.Next; // move to the next address
- }
- }
-
- /// <summary>
- /// ToString override
- /// </summary>
- /// <returns>
- /// A <see cref="System.String"/>
- /// </returns>
- public override string ToString()
- {
- StringBuilder sb = new StringBuilder();
- sb.AppendFormat("Name: {0}\n", Name);
- if(FriendlyName != null)
- {
- sb.AppendFormat("FriendlyName: {0}\n", FriendlyName);
- }
-
- if (GatewayAddress != null)
- {
- sb.AppendFormat("GatewayAddress: {0}\n", GatewayAddress);
- }
-
- sb.AppendFormat("Description: {0}\n", Description);
- foreach(PcapAddress addr in Addresses)
- {
- sb.AppendFormat("Addresses:\n{0}\n", addr);
- }
- sb.AppendFormat("Flags: {0}\n", Flags);
- return sb.ToString();
- }
- }
-}
126 SharpPcap/PcapStatistics.cs
View
@@ -1,126 +0,0 @@
-/*
-This file is part of SharpPcap.
-
-SharpPcap is free software: you can redistribute it and/or modify
-it under the terms of the GNU Lesser General Public License as published by
-the Free Software Foundation, either version 3 of the License, or
-(at your option) any later version.
-
-SharpPcap is distributed in the hope that it will be useful,
-but WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-GNU Lesser General Public License for more details.
-
-You should have received a copy of the GNU Lesser General Public License
-along with SharpPcap. If not, see <http://www.gnu.org/licenses/>.
-*/
-/*
- * Copyright 2009-2010 Chris Morgan <chmorgan@gmail.com>
- */
-using System;
-using System.Runtime.InteropServices;
-
-namespace SharpPcap
-{
- /// <summary>
- /// Adapter statistics, received, dropped packet counts etc
- /// </summary>
- public class PcapStatistics
- {
- /// <value>
- /// Number of packets received
- /// </value>
- public uint ReceivedPackets { get; set; }
-
- /// <value>
- /// Number of packets dropped
- /// </value>
- public uint DroppedPackets { get; set; }
-
- /// <value>
- /// Number of interface dropped packets
- /// </value>
- public uint InterfaceDroppedPackets { get; set; }
-
- /// <summary>
- /// Retrieve pcap statistics from the adapter
- /// </summary>
- /// <param name="pcap_t">
- /// pcap_t* for the adapter
- /// A <see