### Install MRT# via NuGet Source: https://context7.com/uniroma3/compunet/llms.txt Command to add the MRTSharp library to a .NET project using the NuGet package manager. ```bash dotnet add package MRTSharp ``` -------------------------------- ### Manage IP Prefixes with IPPrefix Source: https://context7.com/uniroma3/compunet/llms.txt Shows how to parse, validate, and perform network calculations on IPv4 and IPv6 prefixes using the IPPrefix class. Includes examples of CIDR notation parsing and address family checking. ```csharp using MRTSharp.Model.IP; using System.Net; using System.Net.Sockets; class Program { static void Main() { // Parse from string IPPrefix prefix1 = IPPrefix.Parse("192.168.1.0/24"); Console.WriteLine($"Prefix: {prefix1}"); Console.WriteLine($"CIDR: {prefix1.Cidr}"); Console.WriteLine($"Family: {prefix1.Family}"); Console.WriteLine($"Network: {prefix1.GetNetworkAddress()}"); // Parse from IPAddress IPAddress addr = IPAddress.Parse("10.0.0.0"); IPPrefix prefix2 = IPPrefix.Parse(addr, 8); Console.WriteLine($"Prefix: {prefix2}"); // IPv6 support IPPrefix prefix3 = IPPrefix.Parse("2001:db8::/32"); Console.WriteLine($"IPv6 Prefix: {prefix3}"); Console.WriteLine($"Is IPv6: {prefix3.Family == AddressFamily.InterNetworkV6}"); // Safe parsing with TryParse if (IPPrefix.TryParse("172.16.0.0/12", out IPPrefix prefix4)) { Console.WriteLine($"Parsed: {prefix4}"); } // Equality comparison IPPrefix a = IPPrefix.Parse("10.0.0.0/8"); IPPrefix b = IPPrefix.Parse("10.0.0.0/8"); Console.WriteLine($"Equal: {a.Equals(b)}"); // true } } ``` -------------------------------- ### Parse MRT File into List Source: https://context7.com/uniroma3/compunet/llms.txt Demonstrates how to parse a single MRT file (plain or compressed) into a list of MRTEntry objects. This approach loads all entries into memory. ```csharp using MRTSharp; using System.IO; class Program { static void Main() { FileInfo file = new FileInfo(@"/path/to/rib.20231001.0000.bz2"); List entries = MRTParser.Run(file); Console.WriteLine($"Parsed {entries.Count} MRT entries"); foreach (var entry in entries) { Console.WriteLine($"Entry timestamp: {entry.OriginateTime}"); } } } ``` -------------------------------- ### Parse MRT File with Callback - C# Source: https://gitlab.com/uniroma3/compunet/networks/mrtsharp/-/blob/master/README.md Demonstrates the basic usage of the MRTParser.Run method to parse an MRT file and process each entry using a callback function. This method takes a FileInfo object and a lambda expression for handling MRT entries. ```csharp using MRTSharp; using System.IO; class Program { static void Main() { FileInfo file = new FileInfo(@"path-to-mrt-file"); MRTParser.Run(file, (mrtEntry) => { // Do something with the mrtEntry }); } } ``` -------------------------------- ### IPPrefix - Working with IP Prefixes Source: https://context7.com/uniroma3/compunet/llms.txt IPPrefix represents an IP network prefix (IPv4 or IPv6) with CIDR notation. It provides parsing, validation, and network address calculation for both address families. ```APIDOC ## IPPrefix - Working with IP Prefixes ### Description IPPrefix represents an IP network prefix (IPv4 or IPv6) with CIDR notation. It provides parsing, validation, and network address calculation for both address families. ### Method Static methods for parsing and instance methods for manipulation. ### Endpoint N/A (This is a library class, not an API endpoint) ### Parameters - **IPPrefix.Parse(string cidr)**: Parses an IP prefix from a CIDR notation string. - **IPPrefix.Parse(IPAddress address, int cidrLength)**: Parses an IP prefix from an IPAddress and CIDR length. - **IPPrefix.TryParse(string cidr, out IPPrefix prefix)**: Attempts to parse an IP prefix from a CIDR notation string, returning a boolean indicating success. ### Request Example ```csharp using MRTSharp.Model.IP; using System.Net; using System.Net.Sockets; // Parse from string IPPrefix prefix1 = IPPrefix.Parse("192.168.1.0/24"); Console.WriteLine($"Prefix: {prefix1}"); Console.WriteLine($"CIDR: {prefix1.Cidr}"); Console.WriteLine($"Family: {prefix1.Family}"); Console.WriteLine($"Network: {prefix1.GetNetworkAddress()}"); // Parse from IPAddress IPAddress addr = IPAddress.Parse("10.0.0.0"); IPPrefix prefix2 = IPPrefix.Parse(addr, 8); Console.WriteLine($"Prefix: {prefix2}"); // IPv6 support IPPrefix prefix3 = IPPrefix.Parse("2001:db8::/32"); Console.WriteLine($"IPv6 Prefix: {prefix3}"); Console.WriteLine($"Is IPv6: {prefix3.Family == AddressFamily.InterNetworkV6}"); // Safe parsing with TryParse if (IPPrefix.TryParse("172.16.0.0/12", out IPPrefix prefix4)) { Console.WriteLine($"Parsed: {prefix4}"); } // Equality comparison IPPrefix a = IPPrefix.Parse("10.0.0.0/8"); IPPrefix b = IPPrefix.Parse("10.0.0.0/8"); Console.WriteLine($"Equal: {a.Equals(b)}"); // true ``` ### Response - **IPPrefix** (object) - The parsed IP prefix object. - **bool** - Indicates success or failure for TryParse operations. #### Success Response (200) N/A (This is a library function) #### Response Example ```json { "prefix": "192.168.1.0/24", "cidr": 24, "family": "InterNetwork", "networkAddress": "192.168.1.0" } ``` ``` -------------------------------- ### Process MRT files and directories with MRTParser Source: https://context7.com/uniroma3/compunet/llms.txt Demonstrates how to parse multiple MRT files or entire directories using the MRTParser class. It supports both parallel and sequential processing modes and allows for custom callback functions to handle each entry. ```csharp using MRTSharp; using MRTSharp.Model.MRT; using System.IO; class Program { static void Main() { var files = new List { new FileInfo(@"/path/to/updates.20231001.0000.gz"), new FileInfo(@"/path/to/updates.20231001.0015.gz"), new FileInfo(@"/path/to/updates.20231001.0030.gz") }; List entriesParallel = MRTParser.Run(files, multithreaded: true); Console.WriteLine($"Parallel: {entriesParallel.Count} entries"); List entriesSequential = MRTParser.Run(files, multithreaded: false); Console.WriteLine($"Sequential: {entriesSequential.Count} entries"); DirectoryInfo directory = new DirectoryInfo(@"/path/to/mrt-data/"); MRTParser.Run(directory, (MRTEntry entry) => { Console.WriteLine($"Processing: {entry.OriginateTime}"); }, multithreaded: true); } } ``` -------------------------------- ### Set Custom Logger - C# Source: https://gitlab.com/uniroma3/compunet/networks/mrtsharp/-/blob/master/README.md Shows how to integrate a custom logger with MRT# by using the SetLogger static method. This allows you to capture debug information, such as parsing errors, from the MRTParser. ```csharp MRTParser.SetLogger(yourILoggerVariable); MrtParser.Run(...); ``` -------------------------------- ### Extract RIB data from TABLE_DUMP_V2 files Source: https://context7.com/uniroma3/compunet/llms.txt Shows how to extract and iterate through RIB records from TABLE_DUMP_V2 files. It demonstrates accessing BGP attributes like AS Path, Communities, MED, and Local Preference for specific prefixes. ```csharp using MRTSharp; using MRTSharp.Model.TableDump; using MRTSharp.Model.BGP; using System.IO; class Program { static void Main() { FileInfo file = new FileInfo(@"/path/to/rib.20231001.0000.bz2"); MRTParser.Run(file, (TableDumpRIBRecord record) => { Console.WriteLine($"Prefix: {record.Prefix}"); Console.WriteLine($" Subtype: {record.Subtype}"); Console.WriteLine($" AddPath enabled: {record.HasAddPath()}"); Console.WriteLine($" Number of RIB entries: {record.Entries.Count}"); foreach (var ribEntry in record.Entries) { Console.WriteLine($" Peer: {ribEntry.Peer?.PeerIP}"); Console.WriteLine($" Originate time: {ribEntry.OriginateTime}"); BGPMessageUpdate update = ribEntry.BGPUpdate; if (update != null) { if (update.ASPath != null) { var asNumbers = update.ASPath.SelectMany(e => e.ASNumbers).ToList(); Console.WriteLine($" AS Path: {string.Join(" ", asNumbers)}"); } Console.WriteLine($" Origin: {update.Origin}"); if (update.NextHops != null) Console.WriteLine($" Next Hops: {string.Join(", ", update.NextHops)}"); if (update.Med.HasValue) Console.WriteLine($" MED: {update.Med.Value}"); if (update.LocalPreference.HasValue) Console.WriteLine($" Local Pref: {update.LocalPreference.Value}"); if (update.Communities != null) Console.WriteLine($" Communities: {string.Join(", ", update.Communities)}"); } } }); } } ``` -------------------------------- ### Configure Error Handling in MRTParser Source: https://context7.com/uniroma3/compunet/llms.txt Demonstrates how to toggle exception throwing behavior in the MRTParser. This allows developers to choose between strict error handling or silent skipping of corrupted records. ```csharp using MRTSharp; using System.IO; class Program { static void Main() { // Enable exception throwing for strict error handling MRTParser.SetThrowExceptions(true); try { FileInfo file = new FileInfo(@"/path/to/mrt-file.bz2"); var entries = MRTParser.Run(file); Console.WriteLine($"Successfully parsed {entries.Count} entries"); } catch (Exception ex) { Console.WriteLine($"Parsing failed: {ex.Message}"); } // Disable exception throwing (default behavior) MRTParser.SetThrowExceptions(false); // This will silently skip corrupted entries FileInfo anotherFile = new FileInfo(@"/path/to/another-file.mrt"); var entriesWithSkips = MRTParser.Run(anotherFile); } } ``` -------------------------------- ### Stream Process MRT Entries via Callback Source: https://context7.com/uniroma3/compunet/llms.txt Uses a callback function to process MRT entries one by one as they are parsed. This is the recommended approach for large files to maintain low memory usage. ```csharp using MRTSharp; using MRTSharp.Model.MRT; using System.IO; class Program { static void Main() { FileInfo file = new FileInfo(@"/path/to/updates.20231001.0000.gz"); int entryCount = 0; MRTParser.Run(file, (MRTEntry entry) => { entryCount++; Console.WriteLine($"[{entry.OriginateTime}] Entry type: {entry.GetType().Name}"); }); Console.WriteLine($"Total entries processed: {entryCount}"); } } ``` -------------------------------- ### Monitor BGP Session State Changes from MRT File - C# Source: https://context7.com/uniroma3/compunet/llms.txt This C# code snippet shows how to monitor BGP session state transitions from an MRT file using MRTSharp. It logs the time, peer IP, and state changes (e.g., Idle to Established, Established to Idle). Dependencies include MRTSharp and System.IO. ```csharp using MRTSharp; using MRTSharp.Model.BGP4MP; using System.IO; class Program { static void Main() { FileInfo file = new FileInfo(@"/path/to/updates.20231001.0000.gz"); MRTParser.Run(file, (BGP4MPStateChange stateChange) => { Console.WriteLine($"Time: {stateChange.OriginateTime}"); Console.WriteLine($"Peer: {stateChange.Peers?.PeerIPAddress}"); Console.WriteLine($"State transition: {stateChange.OldState} -> {stateChange.NewState}"); // Detect session establishment if (stateChange.NewState.ToString() == "Established") { Console.WriteLine(" ** BGP session established!"); } // Detect session failures if (stateChange.NewState.ToString() == "Idle" && stateChange.OldState.ToString() == "Established") { Console.WriteLine(" ** BGP session went down!"); } }); } } ``` -------------------------------- ### Configure Custom Logging for MRTParser - C# Source: https://context7.com/uniroma3/compunet/llms.txt This C# code snippet demonstrates how to configure custom logging for the MRTParser using Microsoft.Extensions.Logging.ILogger. This is useful for debugging issues with corrupted files or unparseable fields. Dependencies include MRTSharp and Microsoft.Extensions.Logging. ```csharp using MRTSharp; using Microsoft.Extensions.Logging; using System.IO; class Program { static void Main() { // Create logger (using any ILogger implementation) using var loggerFactory = LoggerFactory.Create(builder => { builder .SetMinimumLevel(LogLevel.Debug) .AddConsole(); }); ILogger logger = loggerFactory.CreateLogger(); // Set the logger before parsing MRTParser.SetLogger(logger); // Now parse - any issues will be logged FileInfo file = new FileInfo(@"/path/to/potentially-corrupted.mrt"); var entries = MRTParser.Run(file); Console.WriteLine($"Parsed {entries.Count} entries (check logs for any warnings)"); } } ``` -------------------------------- ### Parse BGP4MP Messages from MRT File - C# Source: https://context7.com/uniroma3/compunet/llms.txt This C# code snippet demonstrates how to parse BGP4MP messages from a specified MRT file using the MRTSharp library. It accesses message timing, peer information, and processes BGP UPDATE messages, including announcements, withdrawals, and AS paths. Dependencies include MRTSharp and System.IO. ```csharp using MRTSharp; using MRTSharp.Model.BGP4MP; using MRTSharp.Model.BGP; using System.IO; class Program { static void Main() { FileInfo file = new FileInfo(@"/path/to/updates.20231001.0000.gz"); MRTParser.Run(file, (BGP4MPMessage message) => { // Access timing and peer info Console.WriteLine($"Time: {message.OriginateTime}"); Console.WriteLine($"Subtype: {message.Subtype}"); Console.WriteLine($"Peer IP: {message.Peers?.PeerIPAddress}"); Console.WriteLine($"Local IP: {message.Peers?.LocalPeerIPAddress}"); Console.WriteLine($"AS length: {message.GetASLength()} bytes"); Console.WriteLine($"AddPath: {message.HasAddPath()}"); // Check if this is an UPDATE message if (message.Message is BGPMessageUpdate update) { // Process announcements if (update.ContainsAnnouncements()) { Console.WriteLine(" Announcements:"); foreach (var prefix in update.Announcements) { Console.WriteLine($" + {prefix}"); } } // Process withdrawals if (update.ContainsWithdrawals()) { Console.WriteLine(" Withdrawals:"); foreach (var prefix in update.Withdrawals) { Console.WriteLine($" - {prefix}"); } } // Access AS Path if (update.ASPath != null) { foreach (var segment in update.ASPath) { string segmentType = segment.IsAsSet() ? "AS_SET" : "AS_SEQUENCE"; Console.WriteLine($" {segmentType}: {string.Join(" ", segment.ASNumbers)}"); } } } }); } } ``` -------------------------------- ### MRTParser.SetThrowExceptions - Error Handling Source: https://context7.com/uniroma3/compunet/llms.txt Configure whether the parser should throw exceptions on errors or silently skip corrupted records. By default, exceptions are not thrown and corrupted files are logged. ```APIDOC ## MRTParser.SetThrowExceptions - Error Handling ### Description Configure whether the parser should throw exceptions on errors or silently skip corrupted records. By default, exceptions are not thrown and corrupted files are logged. ### Method This is a static method call within the MRTParser class. ### Endpoint N/A (This is a library function, not an API endpoint) ### Parameters - **throwExceptions** (bool) - Required - If true, exceptions will be thrown on parsing errors. If false, errors will be logged and records skipped. ### Request Example ```csharp using MRTSharp; using System.IO; // Enable exception throwing for strict error handling MRTParser.SetThrowExceptions(true); try { FileInfo file = new FileInfo(@"/path/to/mrt-file.bz2"); var entries = MRTParser.Run(file); Console.WriteLine($"Successfully parsed {entries.Count} entries"); } catch (Exception ex) { Console.WriteLine($"Parsing failed: {ex.Message}"); } // Disable exception throwing (default behavior) MRTParser.SetThrowExceptions(false); // This will silently skip corrupted entries FileInfo anotherFile = new FileInfo(@"/path/to/another-file.mrt"); var entriesWithSkips = MRTParser.Run(anotherFile); ``` ### Response This method does not return a value. It configures the behavior of the MRTParser. ``` -------------------------------- ### Parse MRT Files with Type-Filtered Generics Source: https://context7.com/uniroma3/compunet/llms.txt Filters MRT records during parsing by specifying a generic type, such as TableDumpRIBRecord or BGP4MPMessage, which discards non-matching entries automatically. ```csharp using MRTSharp; using MRTSharp.Model.TableDump; using MRTSharp.Model.BGP4MP; using System.IO; class Program { static void Main() { FileInfo ribFile = new FileInfo(@"/path/to/rib.20231001.0000.bz2"); FileInfo updatesFile = new FileInfo(@"/path/to/updates.20231001.0000.gz"); List ribRecords = MRTParser.Run(ribFile); foreach (var record in ribRecords) { Console.WriteLine($"Prefix: {record.Prefix} ({record.Entries.Count} RIB entries)"); } List messages = MRTParser.Run(updatesFile); foreach (var msg in messages) { Console.WriteLine($"BGP Message from peer: {msg.Peers?.PeerIPAddress}"); } List stateChanges = MRTParser.Run(updatesFile); foreach (var change in stateChanges) { Console.WriteLine($"State change: {change.OldState} -> {change.NewState}"); } } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.