### Low-Level SNMPv3 GET Request with Privacy Source: https://context7.com/lextudio/sharpsnmplib/llms.txt For SNMPv3, use GetRequestMessage directly. This requires a prior engine discovery report and a privacy provider. This example uses SHA-256 authentication and AES-128 privacy. ```csharp using System; using System.Collections.Generic; using System.Net; using System.Threading.Tasks; using Lextm.SharpSnmpLib; using Lextm.SharpSnmpLib.Messaging; using Lextm.SharpSnmpLib.Security; var endpoint = new IPEndPoint(IPAddress.Parse("192.168.1.1"), 161); // Step 1: Engine discovery var discovery = Messenger.GetNextDiscovery(SnmpType.GetRequestPdu); ISnmpMessage report = await discovery.GetResponseAsync(endpoint); // Step 2: Build v3 GET with SHA-256 auth + AES-128 privacy var auth = new SHA256AuthenticationProvider(new OctetString("authpassword")); var priv = new AESPrivacyProvider(new OctetString("privpassword"), auth); var variables = new List { new Variable(new ObjectIdentifier("1.3.6.1.2.1.1.1.0")), // sysDescr }; var request = new GetRequestMessage( VersionCode.V3, Messenger.NextMessageId, Messenger.NextRequestId, new OctetString("myUser"), OctetString.Empty, // contextName variables, priv, Messenger.MaxMessageSize, report); ISnmpMessage response = await request.GetResponseAsync(endpoint); var pdu = response.Pdu(); if (pdu.ErrorStatus.ToInt32() != 0) throw new Exception($"Error: {pdu.ErrorStatus}"); foreach (var v in pdu.Variables) Console.WriteLine($"{v.Id} = {v.Data}"); // 1.3.6.1.2.1.1.1.0 = Linux router 5.4.0 ``` -------------------------------- ### Install #SNMP Library via .NET CLI Source: https://github.com/lextudio/sharpsnmplib/blob/master/readme.md Use this command to add the #SNMP library package to your project using the .NET CLI. ```bash dotnet add package Lextm.SharpSnmpLib ``` -------------------------------- ### Synchronous SNMP GET (v1/v2c) with Messenger.Get Source: https://context7.com/lextudio/sharpsnmplib/llms.txt Use Messenger.Get for synchronous SNMP GET requests. Supports v1 and v2c only. The timeout parameter is in milliseconds (0 for infinite). ```csharp using System; using System.Collections.Generic; using System.Net; using Lextm.SharpSnmpLib; using Lextm.SharpSnmpLib.Messaging; var endpoint = new IPEndPoint(IPAddress.Parse("192.168.1.1"), 161); var community = new OctetString("public"); var variables = new List { new Variable(new ObjectIdentifier("1.3.6.1.2.1.1.5.0")), // sysName }; IList result = Messenger.Get(VersionCode.V2, endpoint, community, variables, timeout: 3000); Console.WriteLine($"System name: {result[0].Data}"); // System name: MyRouter ``` -------------------------------- ### Messenger.Get — Synchronous SNMP GET (v1/v2c) Source: https://context7.com/lextudio/sharpsnmplib/llms.txt Synchronous variant of GET. The `timeout` parameter is in milliseconds (0 = infinite). Supports SNMP v1 and v2c only. ```APIDOC ## Messenger.Get — Synchronous SNMP GET (v1/v2c) ### Description Synchronous variant of GET. The `timeout` parameter is in milliseconds (0 = infinite). Supports SNMP v1 and v2c only. ### Method GET (Synchronous) ### Endpoint N/A (Library method) ### Parameters - **VersionCode**: `VersionCode` - The SNMP version (e.g., `VersionCode.V2`). - **endpoint**: `IPEndPoint` - The network endpoint of the SNMP agent. - **community**: `OctetString` - The community string for authentication. - **variables**: `List` - A list of `Variable` objects representing the OIDs to retrieve. - **timeout**: `int` - Timeout in milliseconds (0 for infinite). ### Request Example ```csharp using System; using System.Collections.Generic; using System.Net; using Lextm.SharpSnmpLib; using Lextm.SharpSnmpLib.Messaging; var endpoint = new IPEndPoint(IPAddress.Parse("192.168.1.1"), 161); var community = new OctetString("public"); var variables = new List { new Variable(new ObjectIdentifier("1.3.6.1.2.1.1.5.0")), // sysName }; IList result = Messenger.Get(VersionCode.V2, endpoint, community, variables, timeout: 3000); Console.WriteLine($"System name: {result[0].Data}"); ``` ### Response #### Success Response - **IList**: A list of `Variable` objects containing the retrieved OID values. #### Response Example ``` System name: MyRouter ``` ``` -------------------------------- ### Install #SNMP Library via NuGet Package Manager Source: https://github.com/lextudio/sharpsnmplib/blob/master/readme.md Use this command to add the #SNMP library package to your project using the NuGet Package Manager in Visual Studio. ```powershell Install-Package Lextm.SharpSnmpLib ``` -------------------------------- ### Discover SNMP Agents on the Network with Discoverer Source: https://context7.com/lextudio/sharpsnmplib/llms.txt Broadcasts a GET request to discover SNMP agents. Subscribe to AgentFound and ExceptionRaised events before calling DiscoverAsync. Discovery targets UDP port 161. ```csharp using System; using System.Net; using System.Threading.Tasks; using Lextm.SharpSnmpLib; using Lextm.SharpSnmpLib.Messaging; var discoverer = new Discoverer(); discoverer.AgentFound += (sender, args) => { Console.WriteLine($"Found agent at {args.Agent}"); if (args.Variable != null) Console.WriteLine($" sysDescr: {args.Variable.Data}"); }; discoverer.ExceptionRaised += (sender, args) => { Console.WriteLine($"Discovery error: {args.Exception.Message}"); }; // Broadcast to 255.255.255.255:161 for 2 seconds var broadcastEndpoint = new IPEndPoint(IPAddress.Broadcast, 161); await discoverer.DiscoverAsync(VersionCode.V2, broadcastEndpoint, new OctetString("public"), interval: 2000); Console.WriteLine("Discovery complete."); // Found agent at 192.168.1.1:161 // sysDescr: Cisco IOS Software ``` -------------------------------- ### Discoverer - Discover SNMP Agents Source: https://context7.com/lextudio/sharpsnmplib/llms.txt Broadcasts a GET request to discover SNMP agents on the network. Subscribe to AgentFound and ExceptionRaised events before calling Discover or DiscoverAsync. ```APIDOC ## Discoverer ### Description Broadcasts a GET request over UDP to discover SNMP agents in a subnet. Subscribe to `AgentFound` and `ExceptionRaised` events before calling `Discover` or `DiscoverAsync`. ### Usage Example ```csharp using System; using System.Net; using System.Threading.Tasks; using Lextm.SharpSnmpLib; using Lextm.SharpSnmpLib.Messaging; var discoverer = new Discoverer(); discoverer.AgentFound += (sender, args) => { Console.WriteLine($"Found agent at {args.Agent}"); if (args.Variable != null) Console.WriteLine($" sysDescr: {args.Variable.Data}"); }; discoverer.ExceptionRaised += (sender, args) => { Console.WriteLine($"Discovery error: {args.Exception.Message}"); }; // Broadcast to 255.255.255.255:161 for 2 seconds var broadcastEndpoint = new IPEndPoint(IPAddress.Broadcast, 161); await discoverer.DiscoverAsync(VersionCode.V2, broadcastEndpoint, new OctetString("public"), interval: 2000); Console.WriteLine("Discovery complete."); ``` ### Events - **AgentFound**: Event triggered when an SNMP agent is found. - **ExceptionRaised**: Event triggered when an exception occurs during discovery. ``` -------------------------------- ### Send SNMP v2c INFORM Request Source: https://context7.com/lextudio/sharpsnmplib/llms.txt Use Messenger.SendInformAsync for acknowledged traps. This example shows a v2c INFORM request, which does not require a privacy provider or report message. ```csharp using System; using System.Collections.Generic; using System.Net; using System.Threading.Tasks; using Lextm.SharpSnmpLib; using Lextm.SharpSnmpLib.Messaging; using Lextm.SharpSnmpLib.Security; var receiver = new IPEndPoint(IPAddress.Parse("192.168.1.100"), 162); var community = new OctetString("public"); var enterprise = new ObjectIdentifier("1.3.6.1.4.1.99999.2"); uint timestamp = 11111; var variables = new List { new Variable(new ObjectIdentifier("1.3.6.1.2.1.1.5.0"), new OctetString("InformDevice")), }; // v2c INFORM — no privacy provider or report required await Messenger.SendInformAsync( requestId: Messenger.NextRequestId, VersionCode.V2, receiver, community, OctetString.Empty, // contextName enterprise, timestamp, variables, privacy: null, // null for v2c report: null); // null for v2c Console.WriteLine("INFORM sent and acknowledged."); ``` -------------------------------- ### Create SNMP Variable Bindings for GET and SET Operations Source: https://context7.com/lextudio/sharpsnmplib/llms.txt Represents an SNMP variable binding, pairing an ObjectIdentifier with an ISnmpData value. Used in GET, SET, Walk, and Trap operations. Supports read-only (Null data) and writeable variables with typed SNMP data. ```csharp using System; using Lextm.SharpSnmpLib; // Read-only variable (for GET requests — Data defaults to Null) var getVar = new Variable(new ObjectIdentifier("1.3.6.1.2.1.1.1.0")); Console.WriteLine(getVar); // Variable: Id: 1.3.6.1.2.1.1.1.0; Data: Null // Write variable (for SET requests) var setVar = new Variable( new ObjectIdentifier("1.3.6.1.2.1.1.5.0"), new OctetString("NewHostName")); Console.WriteLine(setVar.Id); // 1.3.6.1.2.1.1.5.0 Console.WriteLine(setVar.Data); // NewHostName // Using typed SNMP data var counterVar = new Variable( new ObjectIdentifier("1.3.6.1.2.1.2.2.1.10.1"), // ifInOctets.1 new Counter32(1048576)); var gaugeVar = new Variable( new ObjectIdentifier("1.3.6.1.2.1.2.2.1.5.1"), // ifSpeed.1 new Gauge32(1000000000)); // 1 Gbps var timeVar = new Variable( new ObjectIdentifier("1.3.6.1.2.1.1.3.0"), // sysUpTime new TimeTicks(123456)); Console.WriteLine($"Counter: {counterVar.Data}"); // 1048576 Console.WriteLine($"Speed: {gaugeVar.Data}"); // 1000000000 Console.WriteLine($"Uptime: {timeVar.Data}"); // 123456 ``` -------------------------------- ### Messenger.GetAsync — Asynchronous SNMP GET (v1/v2c) Source: https://context7.com/lextudio/sharpsnmplib/llms.txt Sends an asynchronous GET request to retrieve one or more OID variable bindings from an SNMP agent. Supports SNMP v1 and v2c. Throws `ErrorException` if the agent returns an error status. ```APIDOC ## Messenger.GetAsync — Asynchronous SNMP GET (v1/v2c) ### Description Sends a GET request to retrieve one or more OID variable bindings from an SNMP agent. Supports SNMP v1 and v2c. Throws `ErrorException` if the agent returns an error status. ### Method GET (Asynchronous) ### Endpoint N/A (Library method) ### Parameters - **VersionCode**: `VersionCode` - The SNMP version (e.g., `VersionCode.V2`). - **endpoint**: `IPEndPoint` - The network endpoint of the SNMP agent. - **community**: `OctetString` - The community string for authentication. - **variables**: `List` - A list of `Variable` objects representing the OIDs to retrieve. ### Request Example ```csharp using System; using System.Collections.Generic; using System.Net; using System.Threading.Tasks; using Lextm.SharpSnmpLib; using Lextm.SharpSnmpLib.Messaging; var endpoint = new IPEndPoint(IPAddress.Parse("192.168.1.1"), 161); var community = new OctetString("public"); var variables = new List { new Variable(new ObjectIdentifier("1.3.6.1.2.1.1.1.0")), // sysDescr new Variable(new ObjectIdentifier("1.3.6.1.2.1.1.3.0")), // sysUpTime }; try { IList result = await Messenger.GetAsync(VersionCode.V2, endpoint, community, variables); foreach (var v in result) { Console.WriteLine($"OID: {v.Id} Value: {v.Data}"); } } catch (ErrorException ex) { Console.WriteLine($"SNMP error: {ex.Message}"); } catch (TimeoutException ex) { Console.WriteLine($"Timeout: {ex.Message}"); } ``` ### Response #### Success Response - **IList**: A list of `Variable` objects containing the retrieved OID values. #### Response Example ``` OID: 1.3.6.1.2.1.1.1.0 Value: Linux router 5.4.0 OID: 1.3.6.1.2.1.1.3.0 Value: 123456 ``` ``` -------------------------------- ### GetRequestMessage Source: https://context7.com/lextudio/sharpsnmplib/llms.txt Provides low-level access for constructing and sending SNMPv3 GET requests, requiring engine discovery, a privacy provider, and a report message. ```APIDOC ## GetRequestMessage — Low-Level SNMPv3 GET For SNMPv3, use `GetRequestMessage` directly with a privacy provider and a prior engine-discovery report message. ### Method `GetRequestMessage` constructor and `GetResponseAsync` method. ### Parameters - `version` (VersionCode): The SNMP version (V3). - `messageId` (int): The unique message ID. - `requestId` (int): The unique request ID. - `userName` (OctetString): The username for authentication. - `contextName` (OctetString): The context name. - `variables` (List): A list of variables to retrieve. - `privacy` (IPrivacyProvider): The privacy provider. - `maxMessageSize` (int): The maximum message size. - `report` (ISnmpMessage): The report message from engine discovery. ### Request Example ```csharp // Step 1: Engine discovery var discovery = Messenger.GetNextDiscovery(SnmpType.GetRequestPdu); ISnmpMessage report = await discovery.GetResponseAsync(endpoint); // Step 2: Build v3 GET with SHA-256 auth + AES-128 privacy var auth = new SHA256AuthenticationProvider(new OctetString("authpassword")); var priv = new AESPrivacyProvider(new OctetString("privpassword"), auth); var variables = new List { new Variable(new ObjectIdentifier("1.3.6.1.2.1.1.1.0")), // sysDescr }; var request = new GetRequestMessage( VersionCode.V3, Messenger.NextMessageId, Messenger.NextRequestId, new OctetString("myUser"), OctetString.Empty, // contextName variables, priv, Messenger.MaxMessageSize, report); ISnmpMessage response = await request.GetResponseAsync(endpoint); ``` ### Response - `ISnmpMessage`: The SNMP response message. - The PDU of the response contains `ErrorStatus` and `Variables`. ``` -------------------------------- ### Asynchronous SNMP GET (v1/v2c) with Messenger.GetAsync Source: https://context7.com/lextudio/sharpsnmplib/llms.txt Use Messenger.GetAsync to retrieve SNMP variables asynchronously. Supports v1 and v2c. Handles ErrorException and TimeoutException. ```csharp using System; using System.Collections.Generic; using System.Net; using System.Threading.Tasks; using Lextm.SharpSnmpLib; using Lextm.SharpSnmpLib.Messaging; var endpoint = new IPEndPoint(IPAddress.Parse("192.168.1.1"), 161); var community = new OctetString("public"); var variables = new List { new Variable(new ObjectIdentifier("1.3.6.1.2.1.1.1.0")), // sysDescr new Variable(new ObjectIdentifier("1.3.6.1.2.1.1.3.0")), // sysUpTime }; try { IList result = await Messenger.GetAsync(VersionCode.V2, endpoint, community, variables); foreach (var v in result) { Console.WriteLine($"OID: {v.Id} Value: {v.Data}"); } // OID: 1.3.6.1.2.1.1.1.0 Value: Linux router 5.4.0 // OID: 1.3.6.1.2.1.1.3.0 Value: 123456 } catch (ErrorException ex) { Console.WriteLine($"SNMP error: {ex.Message}"); } catch (TimeoutException ex) { Console.WriteLine($"Timeout: {ex.Message}"); } ``` -------------------------------- ### Asynchronous SNMP Bulk Walk (GET-BULK, v2c/v3) with Messenger.BulkWalkAsync Source: https://context7.com/lextudio/sharpsnmplib/llms.txt Walks an OID subtree using GET-BULK requests for efficiency with large tables. Supports v2c and v3. maxRepetitions controls variables per request. Requires contextName and privacy/report parameters for v3. ```csharp using System; using System.Collections.Generic; using System.Net; using System.Threading.Tasks; using Lextm.SharpSnmpLib; using Lextm.SharpSnmpLib.Messaging; using Lextm.SharpSnmpLib.Security; var endpoint = new IPEndPoint(IPAddress.Parse("192.168.1.1"), 161); var community = new OctetString("public"); var tableOid = new ObjectIdentifier("1.3.6.1.2.1.2.2"); // ifTable var results = new List(); int rowCount = await Messenger.BulkWalkAsync( VersionCode.V2, endpoint, community, OctetString.Empty, // contextName (empty for v2c) tableOid, results, maxRepetitions: 10, WalkMode.WithinSubtree, privacy: null, // null for v2c report: null); // null for v2c Console.WriteLine($"Interface table rows: {rowCount}"); // Interface table rows: 4 ``` -------------------------------- ### Asynchronous SNMP Walk (GET-NEXT, v1/v2c) with Messenger.WalkAsync Source: https://context7.com/lextudio/sharpsnmplib/llms.txt Walks an OID subtree using GET-NEXT requests. Returns the number of rows if the OID is a table. Use WalkMode.WithinSubtree to stop at the subtree boundary. ```csharp using System; using System.Collections.Generic; using System.Net; using System.Threading.Tasks; using Lextm.SharpSnmpLib; using Lextm.SharpSnmpLib.Messaging; var endpoint = new IPEndPoint(IPAddress.Parse("192.168.1.1"), 161); var community = new OctetString("public"); // Walk the interfaces table (IF-MIB::ifTable) var tableOid = new ObjectIdentifier("1.3.6.1.2.1.2.2"); var results = new List(); int rowCount = await Messenger.WalkAsync( VersionCode.V2, endpoint, community, tableOid, results, WalkMode.WithinSubtree); Console.WriteLine($"Rows found: {rowCount}, Total variables: {results.Count}"); foreach (var v in results) { Console.WriteLine($" {v.Id} = {v.Data}"); } // Rows found: 3, Total variables: 33 // 1.3.6.1.2.1.2.2.1.1.1 = 1 // 1.3.6.1.2.1.2.2.1.2.1 = eth0 // ... ``` -------------------------------- ### Messenger.BulkWalkAsync Source: https://context7.com/lextudio/sharpsnmplib/llms.txt Performs an asynchronous SNMP Bulk Walk (GET-BULK) for more efficient retrieval of large tables. Supports SNMPv2c and v3. ```APIDOC ## Messenger.BulkWalkAsync — Asynchronous SNMP Bulk Walk (GET-BULK, v2c/v3) Walks an OID subtree using GET-BULK requests, which is more efficient for large tables. Supports v2c and v3. `maxRepetitions` controls how many variables are returned per GET-BULK request. ### Method `Task BulkWalkAsync(VersionCode version, EndPoint endpoint, OctetString community, OctetString contextName, ObjectIdentifier oid, IList variables, int maxRepetitions, WalkMode walkMode, ISnmpMessage privacy, ISnmpMessage report)` ### Parameters - **version** (VersionCode) - The SNMP version to use (v2c or v3). - **endpoint** (EndPoint) - The network endpoint of the SNMP agent. - **community** (OctetString) - The community string for authentication (for v2c). - **contextName** (OctetString) - The context name for SNMPv3. - **oid** (ObjectIdentifier) - The starting Object Identifier for the walk. - **variables** (IList) - A list to store the retrieved variables. - **maxRepetitions** (int) - The maximum number of repetitions per GET-BULK request. - **walkMode** (WalkMode) - Specifies how the walk should proceed (e.g., `WalkMode.WithinSubtree`). - **privacy** (ISnmpMessage) - Privacy parameters for SNMPv3 (null for v2c). - **report** (ISnmpMessage) - Report parameters for SNMPv3 (null for v2c). ### Request Example ```csharp using System.Net; using Lextm.SharpSnmpLib; using Lextm.SharpSnmpLib.Messaging; var endpoint = new IPEndPoint(IPAddress.Parse("192.168.1.1"), 161); var community = new OctetString("public"); var tableOid = new ObjectIdentifier("1.3.6.1.2.1.2.2"); // ifTable var results = new List(); int rowCount = await Messenger.BulkWalkAsync( VersionCode.V2, endpoint, community, OctetString.Empty, // contextName (empty for v2c) tableOid, results, maxRepetitions: 10, WalkMode.WithinSubtree, privacy: null, // null for v2c report: null); // null for v2c Console.WriteLine($"Interface table rows: {rowCount}"); ``` ### Response #### Success Response Returns the number of rows found. The `results` list will be populated with `Variable` objects. #### Response Example ``` Interface table rows: 4 ``` ``` -------------------------------- ### Configure SNMPv3 User Registry with Authentication and Privacy Source: https://context7.com/lextudio/sharpsnmplib/llms.txt Maps SNMPv3 usernames to IPrivacyProvider for authentication and encryption. Pass the registry to MessageFactory.ParseMessages or low-level message constructors. Supports multiple users with different security protocols. ```csharp using Lextm.SharpSnmpLib; using Lextm.SharpSnmpLib.Security; // Build a registry for an SNMPv3 agent that supports multiple users var registry = new UserRegistry(new[] { // User 1: SHA-256 authentication, AES-128 privacy new User( new OctetString("adminUser"), new AESPrivacyProvider( new OctetString("privPassword1"), new SHA256AuthenticationProvider(new OctetString("authPassword1")))), // User 2: MD5 authentication, DES privacy new User( new OctetString("readUser"), new DESPrivacyProvider( new OctetString("privPassword2"), new MD5AuthenticationProvider(new OctetString("authPassword2")))), // User 3: SHA-1 authentication, no privacy new User( new OctetString("monitorUser"), new DefaultPrivacyProvider( new SHA1AuthenticationProvider(new OctetString("authPassword3")))), }); Console.WriteLine(registry); // User registry: count: 3 // Look up a user at message-receive time IPrivacyProvider? provider = registry.Find(new OctetString("adminUser")); Console.WriteLine(provider); // AES 128 privacy provider ``` -------------------------------- ### Messenger.WalkAsync Source: https://context7.com/lextudio/sharpsnmplib/llms.txt Performs an asynchronous SNMP Walk (GET-NEXT) to traverse an OID subtree. It returns the number of rows found, which is particularly useful when walking tables. ```APIDOC ## Messenger.WalkAsync — Asynchronous SNMP Walk (GET-NEXT, v1/v2c) Walks an OID subtree using GET-NEXT requests. Returns the number of rows if the OID is a table; otherwise this value is not meaningful. Use `WalkMode.WithinSubtree` to stop at the subtree boundary. ### Method `Task WalkAsync(VersionCode version, EndPoint endpoint, OctetString community, ObjectIdentifier oid, IList variables, WalkMode walkMode)` ### Parameters - **version** (VersionCode) - The SNMP version to use (v1 or v2c). - **endpoint** (EndPoint) - The network endpoint of the SNMP agent. - **community** (OctetString) - The community string for authentication. - **oid** (ObjectIdentifier) - The starting Object Identifier for the walk. - **variables** (IList) - A list to store the retrieved variables. - **walkMode** (WalkMode) - Specifies how the walk should proceed (e.g., `WalkMode.WithinSubtree`). ### Request Example ```csharp using System.Net; using Lextm.SharpSnmpLib; using Lextm.SharpSnmpLib.Messaging; var endpoint = new IPEndPoint(IPAddress.Parse("192.168.1.1"), 161); var community = new OctetString("public"); var tableOid = new ObjectIdentifier("1.3.6.1.2.1.2.2"); // IF-MIB::ifTable var results = new List(); int rowCount = await Messenger.WalkAsync( VersionCode.V2, endpoint, community, tableOid, results, WalkMode.WithinSubtree); Console.WriteLine($"Rows found: {rowCount}, Total variables: {results.Count}"); ``` ### Response #### Success Response Returns the number of rows found. The `results` list will be populated with `Variable` objects. #### Response Example ``` Rows found: 3, Total variables: 33 1.3.6.1.2.1.2.2.1.1.1 = 1 1.3.6.1.2.1.2.2.1.2.1 = eth0 ``` ``` -------------------------------- ### Asynchronous SNMP SET (v1/v2c) with Messenger.SetAsync Source: https://context7.com/lextudio/sharpsnmplib/llms.txt Use Messenger.SetAsync to modify SNMP variable values asynchronously. Supports v1 and v2c. Throws ErrorException on agent-reported errors. ```csharp using System; using System.Collections.Generic; using System.Net; using System.Threading.Tasks; using Lextm.SharpSnmpLib; using Lextm.SharpSnmpLib.Messaging; var endpoint = new IPEndPoint(IPAddress.Parse("192.168.1.1"), 161); var community = new OctetString("private"); // Set sysName (1.3.6.1.2.1.1.5.0) to "NewRouterName" var variables = new List { new Variable(new ObjectIdentifier("1.3.6.1.2.1.1.5.0"), new OctetString("NewRouterName")), }; try { IList result = await Messenger.SetAsync(VersionCode.V2, endpoint, community, variables); Console.WriteLine($"SET succeeded. Returned: {result[0].Data}"); // SET succeeded. Returned: NewRouterName } catch (ErrorException ex) { Console.WriteLine($"SET failed: {ex.Message}"); } ``` -------------------------------- ### Construct and Convert SNMP Object Identifiers (OIDs) Source: https://context7.com/lextudio/sharpsnmplib/llms.txt Represents SNMP OIDs and supports construction from dotted-decimal strings or uint arrays. Enables comparison operators and serialization. OIDs can be extended to represent table entries. ```csharp using System; using Lextm.SharpSnmpLib; // From dotted string var oidFromString = new ObjectIdentifier("1.3.6.1.2.1.1.1.0"); Console.WriteLine(oidFromString); // 1.3.6.1.2.1.1.1.0 // From uint array var oidFromArray = new ObjectIdentifier(new uint[] { 1, 3, 6, 1, 2, 1, 1, 5, 0 }); Console.WriteLine(oidFromArray); // 1.3.6.1.2.1.1.5.0 // Comparison var a = new ObjectIdentifier("1.3.6.1.2.1.1.1.0"); var b = new ObjectIdentifier("1.3.6.1.2.1.1.2.0"); Console.WriteLine(a < b); // True Console.WriteLine(a == b); // False // Extend an OID (e.g., table row index) var tableEntry = new ObjectIdentifier("1.3.6.1.2.1.2.2.1.2"); var withIndex = ObjectIdentifier.Create(tableEntry.ToNumerical(), 1); Console.WriteLine(withIndex); // 1.3.6.1.2.1.2.2.1.2.1 // Convert between string and uint[] uint[] numerical = ObjectIdentifier.Convert("1.3.6.1.4.1.99999"); string dotted = ObjectIdentifier.Convert(numerical); Console.WriteLine(dotted); // 1.3.6.1.4.1.99999 ``` -------------------------------- ### ObjectIdentifier - OID Construction and Conversion Source: https://context7.com/lextudio/sharpsnmplib/llms.txt Represents an SNMP Object Identifier (OID), supporting construction from strings or arrays, comparison, and conversion. ```APIDOC ## ObjectIdentifier ### Description `ObjectIdentifier` represents an SNMP OID. It can be constructed from a dotted-decimal string or a `uint[]` array, and supports comparison operators and serialization. ### Usage Example ```csharp using System; using Lextm.SharpSnmpLib; // From dotted string var oidFromString = new ObjectIdentifier("1.3.6.1.2.1.1.1.0"); Console.WriteLine(oidFromString); // 1.3.6.1.2.1.1.1.0 // From uint array var oidFromArray = new ObjectIdentifier(new uint[] { 1, 3, 6, 1, 2, 1, 1, 5, 0 }); Console.WriteLine(oidFromArray); // 1.3.6.1.2.1.1.5.0 // Comparison var a = new ObjectIdentifier("1.3.6.1.2.1.1.1.0"); var b = new ObjectIdentifier("1.3.6.1.2.1.1.2.0"); Console.WriteLine(a < b); // True Console.WriteLine(a == b); // False // Extend an OID (e.g., table row index) var tableEntry = new ObjectIdentifier("1.3.6.1.2.1.2.2.1.2"); var withIndex = ObjectIdentifier.Create(tableEntry.ToNumerical(), 1); Console.WriteLine(withIndex); // 1.3.6.1.2.1.2.2.1.2.1 // Convert between string and uint[] uint[] numerical = ObjectIdentifier.Convert("1.3.6.1.4.1.99999"); string dotted = ObjectIdentifier.Convert(numerical); Console.WriteLine(dotted); // 1.3.6.1.4.1.99999 ``` ### Methods - **Create(uint[] numerical, params uint[] suffix)**: Creates a new `ObjectIdentifier` by extending an existing numerical OID. - **Convert(string oid)**: Converts a dotted-decimal OID string to a `uint[]` array. - **Convert(uint[] numerical)**: Converts a `uint[]` array to a dotted-decimal OID string. ``` -------------------------------- ### Send SNMPv2c Trap with Messenger.SendTrapV2Async Source: https://context7.com/lextudio/sharpsnmplib/llms.txt Sends a TRAP v2c message to a trap receiver. Only VersionCode.V2 is supported. Enterprise OID and timestamp are embedded in the varbind structure. Requires request ID, receiver, community, enterprise OID, timestamp, and variables. ```csharp using System; using System.Collections.Generic; using System.Net; using System.Threading.Tasks; using Lextm.SharpSnmpLib; using Lextm.SharpSnmpLib.Messaging; var receiver = new IPEndPoint(IPAddress.Parse("192.168.1.100"), 162); var community = new OctetString("public"); var enterprise = new ObjectIdentifier("1.3.6.1.4.1.99999.1"); uint timestamp = 67890; var variables = new List { new Variable(new ObjectIdentifier("1.3.6.1.2.1.1.5.0"), new OctetString("AlertDevice")), }; await Messenger.SendTrapV2Async( requestId: Messenger.NextRequestId, VersionCode.V2, receiver, community, enterprise, timestamp, variables); Console.WriteLine("SNMPv2c trap sent."); ``` -------------------------------- ### Parse Raw SNMP Bytes with MessageFactory Source: https://context7.com/lextudio/sharpsnmplib/llms.txt Use MessageFactory.ParseMessages to decode raw UDP byte buffers into ISnmpMessage objects. A UserRegistry is required for v3 decryption, which should contain known users and their security providers. ```csharp using System; using System.Collections.Generic; using Lextm.SharpSnmpLib; using Lextm.SharpSnmpLib.Messaging; using Lextm.SharpSnmpLib.Security; // Simulate receiving raw bytes from a UDP socket byte[] rawBytes = /* ... bytes from UdpClient.Receive() ... */ Array.Empty(); // For v1/v2c, an empty registry is sufficient var registry = new UserRegistry(); // For v3, add known users: // var auth = new SHA1AuthenticationProvider(new OctetString("authphrase")); // var priv = new AESPrivacyProvider(new OctetString("privphrase"), auth); // registry.Add(new OctetString("myUser"), priv); try { IList messages = MessageFactory.ParseMessages(rawBytes, registry); foreach (var msg in messages) { Console.WriteLine($"Type: {msg.TypeCode()} Version: {msg.Version}"); foreach (var v in msg.Variables()) Console.WriteLine($" {v.Id} = {v.Data}"); } } catch (SnmpException ex) { Console.WriteLine($"Parse error: {ex.Message}"); } ``` -------------------------------- ### Messenger.SendInformAsync Source: https://context7.com/lextudio/sharpsnmplib/llms.txt Sends an acknowledged INFORM request, supporting both v2c and v3 protocols. For v3, a privacy provider and a prior report message are required. ```APIDOC ## Messenger.SendInformAsync — Send INFORM Request (v2c/v3) Sends an INFORM request, which is an acknowledged trap. Supports v2c and v3. For v3, a valid privacy provider and a prior report message (from engine discovery) must be provided. ### Method `SendInformAsync` ### Parameters - `requestId` (int): The unique identifier for the request. - `version` (VersionCode): The SNMP version (V2 or V3). - `receiver` (IPEndPoint): The endpoint of the receiver. - `community` (OctetString): The community string for authentication. - `contextName` (OctetString): The context name for v3. - `enterprise` (ObjectIdentifier): The enterprise OID. - `timestamp` (uint): The timestamp for the PDU. - `variables` (List): A list of variables to send. - `privacy` (IPrivacyProvider): The privacy provider for v3. - `report` (ISnmpMessage): The report message for v3. ### Request Example (v2c) ```csharp await Messenger.SendInformAsync( requestId: Messenger.NextRequestId, VersionCode.V2, receiver, community, OctetString.Empty, // contextName enterprise, timestamp, variables, privacy: null, // null for v2c report: null); // null for v2c ``` ### Response Indicates success if the INFORM request is acknowledged. ``` -------------------------------- ### Messenger.SetAsync — Asynchronous SNMP SET (v1/v2c) Source: https://context7.com/lextudio/sharpsnmplib/llms.txt Sends an asynchronous SET request to write one or more OID values on an SNMP agent. Supports v1 and v2c. Throws `ErrorException` on agent-reported errors. ```APIDOC ## Messenger.SetAsync — Asynchronous SNMP SET (v1/v2c) ### Description Sends a SET request to write one or more OID values on an SNMP agent. Supports v1 and v2c. Throws `ErrorException` on agent-reported errors. ### Method SET (Asynchronous) ### Endpoint N/A (Library method) ### Parameters - **VersionCode**: `VersionCode` - The SNMP version (e.g., `VersionCode.V2`). - **endpoint**: `IPEndPoint` - The network endpoint of the SNMP agent. - **community**: `OctetString` - The community string for authentication. - **variables**: `List` - A list of `Variable` objects representing the OIDs and their new values. ### Request Example ```csharp using System; using System.Collections.Generic; using System.Net; using System.Threading.Tasks; using Lextm.SharpSnmpLib; using Lextm.SharpSnmpLib.Messaging; var endpoint = new IPEndPoint(IPAddress.Parse("192.168.1.1"), 161); var community = new OctetString("private"); // Set sysName (1.3.6.1.2.1.1.5.0) to "NewRouterName" var variables = new List { new Variable(new ObjectIdentifier("1.3.6.1.2.1.1.5.0"), new OctetString("NewRouterName")), }; try { IList result = await Messenger.SetAsync(VersionCode.V2, endpoint, community, variables); Console.WriteLine($"SET succeeded. Returned: {result[0].Data}"); } catch (ErrorException ex) { Console.WriteLine($"SET failed: {ex.Message}"); } ``` ### Response #### Success Response - **IList**: A list of `Variable` objects containing the values returned by the agent after the SET operation. #### Response Example ``` SET succeeded. Returned: NewRouterName ``` ``` -------------------------------- ### UserRegistry - SNMPv3 User Store Source: https://context7.com/lextudio/sharpsnmplib/llms.txt Manages SNMPv3 usernames and their associated privacy providers (authentication and encryption). Used in message parsing and construction. ```APIDOC ## UserRegistry ### Description `UserRegistry` maps SNMPv3 usernames to their `IPrivacyProvider` (which bundles authentication + encryption). It is passed to `MessageFactory.ParseMessages` and to low-level message constructors. ### Usage Example ```csharp using Lextm.SharpSnmpLib; using Lextm.SharpSnmpLib.Security; // Build a registry for an SNMPv3 agent that supports multiple users var registry = new UserRegistry(new[] { // User 1: SHA-256 authentication, AES-128 privacy new User( new OctetString("adminUser"), new AESPrivacyProvider( new OctetString("privPassword1"), new SHA256AuthenticationProvider(new OctetString("authPassword1")))), // User 2: MD5 authentication, DES privacy new User( new OctetString("readUser"), new DESPrivacyProvider( new OctetString("privPassword2"), new MD5AuthenticationProvider(new OctetString("authPassword2")))), // User 3: SHA-1 authentication, no privacy new User( new OctetString("monitorUser"), new DefaultPrivacyProvider( new SHA1AuthenticationProvider(new OctetString("authPassword3")))), }); Console.WriteLine(registry); // User registry: count: 3 // Look up a user at message-receive time IPrivacyProvider? provider = registry.Find(new OctetString("adminUser")); Console.WriteLine(provider); // AES 128 privacy provider ``` ### Methods - **Find(OctetString username)**: Looks up and returns the `IPrivacyProvider` for the given username. ``` -------------------------------- ### Send SNMPv1 Trap with Messenger.SendTrapV1Async Source: https://context7.com/lextudio/sharpsnmplib/llms.txt Sends a TRAP v1 message to a trap receiver, typically listening on UDP port 162. Requires receiver endpoint, agent address, community, enterprise OID, trap type, specific code, timestamp, and variables. ```csharp using System; using System.Collections.Generic; using System.Net; using System.Threading.Tasks; using Lextm.SharpSnmpLib; using Lextm.SharpSnmpLib.Messaging; var receiver = new IPEndPoint(IPAddress.Parse("192.168.1.100"), 162); var agentAddress = IPAddress.Parse("192.168.1.1"); var community = new OctetString("public"); var enterprise = new ObjectIdentifier("1.3.6.1.4.1.99999"); uint timestamp = 12345; var variables = new List { new Variable(new ObjectIdentifier("1.3.6.1.2.1.1.5.0"), new OctetString("AlertRouter")), }; await Messenger.SendTrapV1Async( receiver, agentAddress, community, enterprise, GenericCode.ColdStart, specific: 0, timestamp, variables); Console.WriteLine("SNMPv1 trap sent."); ``` -------------------------------- ### MessageFactory.ParseMessages Source: https://context7.com/lextudio/sharpsnmplib/llms.txt Parses raw SNMP byte buffers into ISnmpMessage objects, essential for SNMP agents and trap listeners. Requires a UserRegistry for v3 decryption. ```APIDOC ## MessageFactory.ParseMessages — Parse Raw SNMP Bytes Parses one or more raw UDP byte buffers into `ISnmpMessage` objects. Used by SNMP agents or trap listeners to decode incoming packets. A `UserRegistry` must be provided for v3 decryption. ### Method `ParseMessages` ### Parameters - `rawBytes` (byte[]): The raw byte buffer received from a UDP socket. - `registry` (UserRegistry): A registry of users for v3 decryption. Can be empty for v1/v2c. ### Request Example ```csharp // Simulate receiving raw bytes from a UDP socket byte[] rawBytes = /* ... bytes from UdpClient.Receive() ... */ Array.Empty(); // For v1/v2c, an empty registry is sufficient var registry = new UserRegistry(); // For v3, add known users: // var auth = new SHA1AuthenticationProvider(new OctetString("authphrase")); // var priv = new AESPrivacyProvider(new OctetString("privphrase"), auth); // registry.Add(new OctetString("myUser"), priv); try { IList messages = MessageFactory.ParseMessages(rawBytes, registry); foreach (var msg in messages) { Console.WriteLine($"Type: {msg.TypeCode()} Version: {msg.Version}"); foreach (var v in msg.Variables()) Console.WriteLine($" {v.Id} = {v.Data}"); } } catch (SnmpException ex) { Console.WriteLine($"Parse error: {ex.Message}"); } ``` ### Response - `IList`: A list of parsed SNMP messages. - Throws `SnmpException` if parsing fails. ```