From 51528e5f09709374bfb008603469ddeef60808ba Mon Sep 17 00:00:00 2001 From: Andreas Venizelou Date: Wed, 20 Mar 2024 16:56:06 +0200 Subject: [PATCH] SNMP polling --- Protest/Protest.csproj | 2 +- Protest/Protocols/Snmp.Polling.cs | 51 +++++++++++++++++++++++-------- 2 files changed, 40 insertions(+), 13 deletions(-) diff --git a/Protest/Protest.csproj b/Protest/Protest.csproj index 49c93a8a..f9e3dbdf 100644 --- a/Protest/Protest.csproj +++ b/Protest/Protest.csproj @@ -57,7 +57,7 @@ - + diff --git a/Protest/Protocols/Snmp.Polling.cs b/Protest/Protocols/Snmp.Polling.cs index 26f0533d..d2c13e27 100644 --- a/Protest/Protocols/Snmp.Polling.cs +++ b/Protest/Protocols/Snmp.Polling.cs @@ -1,36 +1,63 @@ using Lextm.SharpSnmpLib; using Lextm.SharpSnmpLib.Messaging; +using Lextm.SharpSnmpLib.Security; + using System.Collections.Generic; using System.Net; +using System.Text; +using System.Threading; using System.Threading.Tasks; namespace Protest.Protocols.Snmp; internal static class Polling { - public static async Task PollAsync(IPAddress target, string communityString, string oidString) { - VersionCode version = VersionCode.V3; + + public static byte[] Poll(IPAddress target, string community, string oid, int timeout) { + byte[] bytes = null; + + Task.Run(async () => { + try { + IList result = await PollAsync(target, community, oid, timeout); + bytes = Encoding.UTF8.GetBytes(result[0].Data.ToString()); + } + catch (Exception ex) { + bytes = Encoding.UTF8.GetBytes(ex.Message); + } + }).GetAwaiter().GetResult(); + + return bytes; + } + + private static async Task> PollAsync(IPAddress target, string communityString, string oidString, int timeout) { + VersionCode version = VersionCode.V2; IPEndPoint endpoint = new IPEndPoint(target, 161); OctetString community = new OctetString(communityString); ObjectIdentifier oid = new ObjectIdentifier(oidString); List variables = new List { new Variable(oid) }; - IList result = await Messenger.GetAsync(version, endpoint, community, variables); + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(timeout); + CancellationToken cancellationToken = cancellationTokenSource.Token; - if (result is null) { - Console.WriteLine("No data received."); - return; + IList result; + try { + result = await Messenger.GetAsync(version, endpoint, community, variables, cancellationToken); + } + catch (OperationCanceledException) { + throw new Exception("Operation timed out"); + } + catch (Exception) { + throw; } + if (result is null) { + throw new Exception("No data received"); + } if (result.Count == 0) { - Console.WriteLine("No result received."); - return; + throw new Exception("No result received"); } - Console.WriteLine("The value of OID {0} is {1}", oid, result[0].Data.ToString()); + return result; } - public static async void Test() { - await PollAsync(IPAddress.Parse("127.0.0.1"), "public", ""); - } } \ No newline at end of file