IPMonitor Component
Properties Methods Events Config Settings Errors
The IPMonitor class allows applications to monitor network packets on multiple platforms.
Syntax
pcapfilter.IPMonitor
Remarks
IPMonitor is a lightweight struct that allows applications to monitor network activity across multiple platforms, including Windows, Linux, and macOS. It utilizes the "libpcap" library and underlying network drivers to capture and report network packets in real-time. The struct provides the ability to capture individual network packets for detailed analysis, or collect aggregated packet statistics for monitoring network performance.
Setup
Before using the struct, a libpcap-compatible network library must be installed on the system. For detailed installation instructions, please refer to the Network Filter Library section. This setup only needs to be done once.Linux and macOS
For Linux and macOS systems, permissions may need to be adjusted as described in the System Configuration in Linux and macOS instructions page to allow the application to capture packets.
Retrieving Network Adapters
The first step in using the struct is to identify the name of the network adapter that will be monitored. To retrieve the list of network adapters available on the system, call the ListAdapters method. Once the method is called, the adapters will be accessible via the Adapters property.// Retrieve the list of network adapters available on the system
ipmonitor.ListAdapters();
// Display the available adapters
foreach (Adapter adapter in ipmonitor.Adapters)
{
Console.WriteLine($"Adapter Name: {adapter.Name}");
Console.WriteLine($"Description: {adapter.Description}");
}
Packet Filters
Before starting to monitor a network adapter, filters can be applied to capture only the packets that match certain criteria.The Direction property can be used to specify whether to capture incoming packets, outgoing packets, or both. In addition to directionality, the Filter property can be set to a pcap filter expression string that allows for filtering based on IP addresses, protocol types, ports, and more. For more information on supported filter expressions, please see the pcap-filter(7) man page.
// Only capture incoming packets
ipmonitor.Direction = callback.PCAPFilter.Constants.PACKET_DIRECTION_INCOMING;
// Only capture TCP packets from IP 192.168.1.1 on port 80
ipmonitor.Filter = "src host 192.168.1.1 and tcp port 80";
Operation Modes
In addition to packet filters, the struct supports multiple operation modes that determine what kind of packet information will be reported.Capture Mode
Setting the OperationMode property to PCAP_MODE_CAPT will cause the struct to capture individual network packets and report them through the Packet event.
// Capture individual packet information
ipmonitor.OperationMode = (int)OperationModes.PCAP_MODE_CAPT;
Statistical Mode
Setting the OperationMode property to PCAP_MODE_STAT will instead cause the struct to collect aggregated packet statistics and report them through the Statistics event.
// Report aggregated packet statistics
ipmonitor.OperationMode = (int)OperationModes.PCAP_MODE_STAT;
Monitoring an Adapter
After configuring the filters and operation mode, start monitoring the network adapter by calling the Activate method and specifying the adapter name.// Get the name of the first adapter returned by ListAdapters()
ipmonitor.ListAdapters();
string adapterToMonitor = ipmonitor.Adapters[0].Name;
// Start monitoring the adapter
ipmonitor.Activate(adapterToMonitor);
Retrieving Packet Information
Depending on the current OperationMode, packet information is retrieved differently. In both modes, the DoEvents method must be called to prompt the struct to fire events and report packet information.Capture Mode:
In capture mode, calling DoEvents will cause the struct to process any packets captured by the struct and fire the Packet for each one.
ipmonitor.OnPacket += (s, e) =>
{
// Print out information about each individual packet
Console.WriteLine($"Packet captured at {e.TimeStamp}");
Console.WriteLine($"Packet Size: {e.PacketSize} bytes");
};
Statistical Mode:
In statistical mode, calling DoEvents will prompt the struct to collect packet statistics and report them through the Statistics event.
ipmonitor.OnStatistics += (s, e) =>
{
// Print out packet statistics
Console.WriteLine($"Statistics collected at {e.TimeStamp}");
Console.WriteLine($"Packets Captured: {e.CapturedPackets}");
Console.WriteLine($"Bytes Captured: {e.CapturedBytes}");
};
Capture Statistics
Regardless of the current OperationMode, cumulative statistics about the packets captured since monitoring began can be retrieved by calling the GetStatistics method.long receivedPackets = 0; // The number of packets received since monitoring began
long droppedPackets = 0; // The number of packets dropped by the component since monitoring began
long adapterDroppedPackets = 0; // The number of packets dropped by the adapter since monitoring began
ipmonitor.GetStatistics(ref receivedPackets, ref droppedPackets, ref adapterDroppedPackets);
Console.WriteLine($"Packets Received: {receivedPackets}");
Console.WriteLine($"Packets Dropped: {droppedPackets}");
Console.WriteLine($"Packets Dropped by Adapter: {adapterDroppedPackets}");
Deactivating Monitoring
To stop monitoring the adapter and cease reporting packets, call the Deactivate method.ipmonitor.Deactivate();
Property List
The following is the full list of the properties of the component with short descriptions. Click on the links for further details.
Active | Indicates whether the class is active and monitoring network traffic. |
AdapterCount | The number of records in the Adapter arrays. |
AdapterDescription | Description of the adapter. |
AdapterName | The name of the adapter. |
Direction | Specifies the direction of packets to capture. |
Filter | Specifies filter criteria used to determine which network packets are captured. |
OperationMode | Specifies the mode of operation. |
Tag | This property stores application-defined data specific to a particular instance of the class. |
Method List
The following is the full list of the methods of the component with short descriptions. Click on the links for further details.
Activate | Starts monitoring network traffic. |
Config | Sets or retrieves a configuration setting. |
Deactivate | Stops monitoring network traffic. |
DoEvents | Processes events from the internal message queue. |
GetStatistics | Retrieves the total number of packets received and dropped since monitoring began. |
ListAdapters | Retrieves the network adapters available for monitoring. |
Event List
The following is the full list of the events fired by the component with short descriptions. Click on the links for further details.
Error | This event fires if an unhandled error occurs during an event. |
Packet | Fires when a network packet is captured. |
Statistics | Fires to provide aggregated packet statistics. |
Config Settings
The following is a list of config settings for the component with short descriptions. Click on the links for further details.
BufferSize | The size of the buffer that the driver should use to store packets. |
MaxPacketSize | The number of bytes of a packet to report. |
PacketTimeout | The time to wait for a packet. |
PromiscuousMode | Whether the driver should capture packets where a local system is neither a source or the destination of a packet. |
WiFiMonitorMode | Whether the adapter should work in monitor mode (available in Wi-Fi adapters). |
BuildInfo | Information about the product's build. |
LicenseInfo | Information about the current license. |
Active Property (IPMonitor Component)
Indicates whether the class is active and monitoring network traffic.
Syntax
func (obj *IPMonitor) Active() (bool, error)
Default Value
false
Remarks
This property reflects whether the struct is actively monitoring network traffic. It is automatically set to true after a successful call to Activate, and to false when monitoring is stopped with the Deactivate method.
This property is read-only.
Data Type
bool
AdapterCount Property (IPMonitor Component)
The number of records in the Adapter arrays.
Syntax
func (obj *IPMonitor) AdapterCount() (int32, error)
Default Value
0
Remarks
This property controls the size of the following arrays:
The array indices start at 0 and end at AdapterCount - 1.This property is read-only.
Data Type
int32
AdapterDescription Property (IPMonitor Component)
Description of the adapter.
Syntax
func (obj *IPMonitor) AdapterDescription(AdapterIndex int32) (string, error)
Default Value
""
Remarks
Description of the adapter.
The AdapterIndex parameter specifies the index of the item in the array. The size of the array is controlled by the AdapterCount property.
This property is read-only.
Data Type
string
AdapterName Property (IPMonitor Component)
The name of the adapter.
Syntax
func (obj *IPMonitor) AdapterName(AdapterIndex int32) (string, error)
Default Value
""
Remarks
The name of the adapter. This value can be passed into the Activate method to start monitoring the adapter.
The AdapterIndex parameter specifies the index of the item in the array. The size of the array is controlled by the AdapterCount property.
This property is read-only.
Data Type
string
Direction Property (IPMonitor Component)
Specifies the direction of packets to capture.
Syntax
func (obj *IPMonitor) Direction() (int32, error)
func (obj *IPMonitor) SetDirection(value int32) error
Default Value
0
Remarks
The property makes it possible to capture just outgoing or just incoming packets, working as a simple filter for the network packets. The property value can be one of the following:
PACKET_DIRECTION_ANY | 0x00 | All packets are processed. |
PACKET_DIRECTION_INCOMING | 0x01 | Incoming packets are processed. |
PACKET_DIRECTION_OUTGOING | 0x02 | Outgoing packets are processed. |
Data Type
int32
Filter Property (IPMonitor Component)
Specifies filter criteria used to determine which network packets are captured.
Syntax
func (obj *IPMonitor) Filter() (string, error)
func (obj *IPMonitor) SetFilter(value string) error
Default Value
""
Remarks
This property specifies a filter expression string that determines which network packets are captured and reported. For additional filtering, the Direction property can be used to limit packet capture to incoming or outgoing traffic.
This property can be set before or after calling Activate to start monitoring. In some platforms, changing the value of this property while monitoring is active may result in some packets being dropped or reported even if they do not match the new filter rules. For more details on platform-specific behavior, please see the pcap-filter(7) man page.
Filter Expression Syntax
The filter expression follows the syntax used by libpcap. A filter takes the form of a series of conditions that specify the criteria packets must meet to be captured. Expressions can be combined using conjunctions and, or, and optionally preceded by not.[not] condition [and|or [not] condition ... ]
For more comprehensive information on filter expressions, please refer to the pcap-filter(7) documentation. Below is a simplified overview of common filter expressions:
src|dst host <host> | Captures packets to or from the specified IP address or name. |
src host <host> | Captures packets where the source is the specified host. |
dst host <host> | Captures packets where the destination is the specified host. |
net <network> | Captures packets to or from the specified network. |
src net <network> | Captures packets where the source is in the specified network. |
dst net <network> | Captures packets where the destination is in the specified network. |
port <port> | Captures packets to or from the specified port. |
src port <port> | Captures packets where the source port is the specified port. |
dst port <port> | Captures packets where the destination port is the specified port. |
ether broadcast | Captures all Ethernet broadcast packets. |
ether multicast | Captures all Ethernet multicast packets. |
greater <length> | Captures packets with a length greater than or equal to the specified length (in bytes). |
less <length> | Captures packets with a length lesser than or equal to the specified length (in bytes). |
broadcast | Captures all broadcast packets (Ethernet and IP). |
broadcast | Captures all multicast packets (Ethernet and IP). |
<protocol> | Captures all packets using the specified protocol. |
Example (Simple):
// Only capture packets to and from IP 192.168.1.1
ipmonitor.Filter = "host 192.168.1.1";
Example (Advanced):
// Only capture TCP packets from IP 192.168.1.1 on port 80
ipmonitor.Filter = "src host 192.168.1.1 and tcp port 80";
Data Type
string
OperationMode Property (IPMonitor Component)
Specifies the mode of operation.
Syntax
func (obj *IPMonitor) OperationMode() (int32, error)
func (obj *IPMonitor) SetOperationMode(value int32) error
Default Value
0
Remarks
This property determines the type of packet information to report when DoEvents is called. The property value can be one of the following:
PCAP_MODE_CAPT | 0x00 | Capture mode.
Individual packets are reported through the Packet event as they are received from the network driver. Only packets that match the filter criteria specified in Filter and Direction will trigger the event. |
PCAP_MODE_STAT | 0x01 | Statistical mode.
The struct does not report individual packets. Instead, it will collect packet statistics and provide aggregated packet data via the Statistics event. |
Data Type
int32
Tag Property (IPMonitor Component)
This property stores application-defined data specific to a particular instance of the class.
Syntax
func (obj *IPMonitor) Tag() (int64, error)
func (obj *IPMonitor) SetTag(value int64) error
Default Value
0
Remarks
This property can be used to store data specific to a particular instance of the struct.
Data Type
int64
Activate Method (IPMonitor Component)
Starts monitoring network traffic.
Syntax
func (obj *IPMonitor) Activate(Adapter string) error
Remarks
This method enables monitoring network packets on a specified network adapter. To disable monitoring, call Deactivate instead.
When this method is called, the struct will begin monitoring the specified adapter for network activity. Packets will be captured and reported differently depending on the value of the OperationMode property. Once monitoring is active, the Active property will be automatically set to true.
Adapter specifies the name of the network adapter to monitor. The list of available adapters can be obtained via the ListAdapters method.
Packet Reporting
When Active is set to true, the struct will report packet information based on the value of the OperationMode property. The following operation modes determine how packets are processed and reported:PCAP_MODE_CAPT | 0x00 | Capture mode.
Individual packets are reported through the Packet event as they are received from the network driver. Only packets that match the filter criteria specified in Filter and Direction will trigger the event. |
PCAP_MODE_STAT | 0x01 | Statistical mode.
The struct does not report individual packets. Instead, it will collect packet statistics and provide aggregated packet data via the Statistics event. |
Config Method (IPMonitor Component)
Sets or retrieves a configuration setting.
Syntax
func (obj *IPMonitor) Config(ConfigurationString string) (string, error)
Remarks
Config is a generic method available in every struct. It is used to set and retrieve configuration settings for the struct.
These settings are similar in functionality to properties, but they are rarely used. In order to avoid "polluting" the property namespace of the struct, access to these internal properties is provided through the Config method.
To set a configuration setting named PROPERTY, you must call Config("PROPERTY=VALUE"), where VALUE is the value of the setting expressed as a string. For boolean values, use the strings "True", "False", "0", "1", "Yes", or "No" (case does not matter).
To read (query) the value of a configuration setting, you must call Config("PROPERTY"). The value will be returned as a string.
Deactivate Method (IPMonitor Component)
Stops monitoring network traffic.
Syntax
func (obj *IPMonitor) Deactivate() error
Remarks
This method stops monitoring network traffic. Once called, the struct will cease capturing packets and the Active property will be automatically set to false.
DoEvents Method (IPMonitor Component)
Processes events from the internal message queue.
Syntax
func (obj *IPMonitor) DoEvents() error
Remarks
This method processes events from the internal message queue and fires the corresponding events based on the current OperationMode. It should be called periodically to prompt the struct to fire events and report packet information.
Capture Modes
This method behaves differently depending on the value of the OperationMode property.When OperationMode is set to PCAP_MODE_CAPT, calling this method while monitoring is active will prompt the struct to process any packets captured since the last call and fire the Packet event for each one. If there are no new packets to report, the method will wait for a duration specified by the PacketTimeout configuration setting before returning.
If OperationMode is set to PCAP_MODE_STAT, calling this method will instead tell the struct to collect packet statistics since the last call and fire the Statistics event with the aggregated data.
GetStatistics Method (IPMonitor Component)
Retrieves the total number of packets received and dropped since monitoring began.
Syntax
func (obj *IPMonitor) GetStatistics(Received *int64, Dropped *int64, AdapterDropped *int64) error
Remarks
This method provides capture statistics about the packets monitored by the struct and the underlying driver since Activate was called to start monitoring.
The Received parameter provides the number of packets received since monitoring began.
The Dropped parameter provides the number of packets that were dropped since monitoring began. Packets may be dropped if BufferSize is too small to keep all of the data, or because DoEvents was called too infrequently.
The AdapterDropped parameter provides the full number of packets that were dropped by the network adapter since monitoring began.
Platform Differences
This method is platform-dependent. It uses the underlying pcap_stats() function from the libpcap library to retrieve packet statistics, which may cause the values provided in the Received, Dropped, and AdapterDropped parameters to differ depending on the platform.
- Received: On some platforms, this count may include all packets, regardless of whether they matched the filter criteria set using Filter.
- Dropped: This value may not be available on all platforms.
- AdapterDropped: This count might not be implemented on some platforms. If its value is 0, it could indicate either no drops or that the statistic is unavailable.
For more information regarding platform differences, please see the pcap_stats() documentation.
ListAdapters Method (IPMonitor Component)
Retrieves the network adapters available for monitoring.
Syntax
func (obj *IPMonitor) ListAdapters() error
Remarks
This method populates the Adapters collection with a list of network adapters available for monitoring. Each adapter in the collection includes a name and description provided by the network driver.
This method can be used to obtain the name of a network adapter before calling Activate to start monitoring it.
Example:
// Populate the 'Adapters' collection with the list of available network adapters
ipmonitor.ListAdapters();
// Start monitoring the first adapter in the collection
ipmonitor.Activate(ipmonitor.Adapters[0].Name);
Error Event (IPMonitor Component)
This event fires if an unhandled error occurs during an event.
Syntax
// IPMonitorErrorEventArgs carries the IPMonitor Error event's parameters. type IPMonitorErrorEventArgs struct {...} func (args *IPMonitorErrorEventArgs) ErrorCode() int32 func (args *IPMonitorErrorEventArgs) Description() string // IPMonitorErrorEvent defines the signature of the IPMonitor Error event's handler function. type IPMonitorErrorEvent func(sender *IPMonitor, args *IPMonitorErrorEventArgs) func (obj *IPMonitor) GetOnErrorHandler() IPMonitorErrorEvent func (obj *IPMonitor) SetOnErrorHandler(handlerFunc IPMonitorErrorEvent)
Remarks
This event fires if an unhandled error occurs during another event. Developers can use this information to track down unhandled errors in an application's event handlers.
Packet Event (IPMonitor Component)
Fires when a network packet is captured.
Syntax
// IPMonitorPacketEventArgs carries the IPMonitor Packet event's parameters. type IPMonitorPacketEventArgs struct {...} func (args *IPMonitorPacketEventArgs) TimeStamp() time.Time func (args *IPMonitorPacketEventArgs) PacketSize() int32 func (args *IPMonitorPacketEventArgs) Data() []byte func (args *IPMonitorPacketEventArgs) DataSize() int32 // IPMonitorPacketEvent defines the signature of the IPMonitor Packet event's handler function. type IPMonitorPacketEvent func(sender *IPMonitor, args *IPMonitorPacketEventArgs) func (obj *IPMonitor) GetOnPacketHandler() IPMonitorPacketEvent func (obj *IPMonitor) SetOnPacketHandler(handlerFunc IPMonitorPacketEvent)
Remarks
This event fires for each packet received from the monitored network adapter. The event will only fire if OperationMode is set to PCAP_MODE_CAPT and the captured packet matches the filter criteria specified in Filter and Direction. Packets are reported in the order they are received from the network adapter.
The Timestamp parameter contains the time when the packet was received by the network adapter.
The PacketSize parameter contains the total size of the packet as received by the network adapter. This represents the full byte size of the packet, which may be larger than the amount of data captured in the Data parameter.
The Data parameter contains the packet data that was captured. The amount of data captured is controlled by the MaxPacketSize configuration setting, and it may be smaller than the full packet size.
The DataSize parameter provides the size of the data contained in the Data parameter. This value represents how much of the packet data was actually captured and made available.
Packet Reporting
When Active is set to true, the struct will report packet information based on the value of the OperationMode property. The following operation modes determine how packets are processed and reported:PCAP_MODE_CAPT | 0x00 | Capture mode.
Individual packets are reported through the Packet event as they are received from the network driver. Only packets that match the filter criteria specified in Filter and Direction will trigger the event. |
PCAP_MODE_STAT | 0x01 | Statistical mode.
The struct does not report individual packets. Instead, it will collect packet statistics and provide aggregated packet data via the Statistics event. |
Statistics Event (IPMonitor Component)
Fires to provide aggregated packet statistics.
Syntax
// IPMonitorStatisticsEventArgs carries the IPMonitor Statistics event's parameters. type IPMonitorStatisticsEventArgs struct {...} func (args *IPMonitorStatisticsEventArgs) TimeStamp() time.Time func (args *IPMonitorStatisticsEventArgs) CapturedPackets() int64 func (args *IPMonitorStatisticsEventArgs) CapturedBytes() int64 // IPMonitorStatisticsEvent defines the signature of the IPMonitor Statistics event's handler function. type IPMonitorStatisticsEvent func(sender *IPMonitor, args *IPMonitorStatisticsEventArgs) func (obj *IPMonitor) GetOnStatisticsHandler() IPMonitorStatisticsEvent func (obj *IPMonitor) SetOnStatisticsHandler(handlerFunc IPMonitorStatisticsEvent)
Remarks
This event fires to provide aggregated packet statistics collected from the network adapter. The event will only fire if OperationMode is set to PCAP_MODE_STAT. Calling DoEvents while monitoring is active will prompt the struct to report packet statistics and fire this event.
The TimeStamp parameter contains the time when the packet statistics were collected.
The CapturedPackets parameter contains the number of packets captured since the last time the event was fired.
The CapturedBytes parameter contains the total byte size of the packets captured since the last time the event was fired.
Packet Reporting
When Active is set to true, the struct will report packet information based on the value of the OperationMode property. The following operation modes determine how packets are processed and reported:PCAP_MODE_CAPT | 0x00 | Capture mode.
Individual packets are reported through the Packet event as they are received from the network driver. Only packets that match the filter criteria specified in Filter and Direction will trigger the event. |
PCAP_MODE_STAT | 0x01 | Statistical mode.
The struct does not report individual packets. Instead, it will collect packet statistics and provide aggregated packet data via the Statistics event. |
Config Settings (IPMonitor Component)
The struct accepts one or more of the following configuration settings. Configuration settings are similar in functionality to properties, but they are rarely used. In order to avoid "polluting" the property namespace of the struct, access to these internal properties is provided through the Config method.IPMonitor Config Settings
The value must be specified in bytes. The default value of 0 tells libpcap to use the default value hard-coded in it. In Windows, this is 1 000 000 bytes (approx.1 megabyte); in Linux, this is 2MB.
The setting corresponds to the pcap_set_buffer_size() function.
In Linux and macOS, this configuration setting can be changed only when the struct is not activated (Active is false).
The value must be specified in bytes. The default value of 0 tells libpcap to set the maximum length to 262 144 bytes.
The setting corresponds to the pcap_set_snaplen() function.
This configuration setting can be changed only when the struct is not activated (Active is false).
The value must be specified in milliseconds. The behavior if a zero or a negative value is set is not defined by libpcap, thus, it is recommended to always set the value to a positive number. The default value is 1000 ms (one second).
The setting corresponds to the pcap_set_timeout() function.
This configuration setting can be changed only when the struct is not activated (Active is false).
By default, the setting is disabled.
The setting corresponds to the pcap_set_promisc() function.
This configuration setting can be changed only when the struct is not activated (Active is false).
The setting corresponds to the pcap_set_rfmon() function.
This configuration setting can be changed only when the struct is not activated (Active is false).
Base Config Settings
- Product: The product the license is for.
- Product Key: The key the license was generated from.
- License Source: Where the license was found (e.g., RuntimeLicense, License File).
- License Type: The type of license installed (e.g., Royalty Free, Single Server).