forked from rqx110/SnmpSharpNet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SimpleSnmp.cs
1154 lines (1134 loc) · 33 KB
/
SimpleSnmp.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// This file is part of SNMP#NET.
//
// SNMP#NET is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// SNMP#NET 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 General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with SNMP#NET. If not, see <http://www.gnu.org/licenses/>.
//
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
namespace SnmpSharpNet
{
/// <summary>
/// Utility class to enable simplified access to SNMP version 1 and version 2 requests and replies.
/// </summary>
/// <remarks>
/// Use this class if you are not looking for "deep" SNMP functionality. Design of the class is based
/// around providing simplest possible access to SNMP operations without getting stack into details.
///
/// If you are using the simplest way, you will leave SuppressExceptions flag to true and get all errors causing methods to return "null" result
/// which will not tell you why operation failed. You can change the SuppressExceptions flag to false and catch any and all
/// exception throwing errors.
///
/// Either way, have fun.
/// </remarks>
public class SimpleSnmp
{
/// <summary>
/// SNMP Agents IP address
/// </summary>
protected IPAddress _peerIP;
/// <summary>
/// SNMP Agents name
/// </summary>
protected string _peerName;
/// <summary>
/// SNMP Agent UDP port number
/// </summary>
protected int _peerPort;
/// <summary>
/// Target class
/// </summary>
protected UdpTarget _target;
/// <summary>
/// Timeout value in milliseconds
/// </summary>
protected int _timeout;
/// <summary>
/// Maximum retry count excluding the first request
/// </summary>
protected int _retry;
/// <summary>
/// SNMP community name
/// </summary>
protected string _community;
/// <summary>
/// Non repeaters value used in SNMP GET-BULK requests
/// </summary>
protected int _nonRepeaters = 0;
/// <summary>
/// Maximum repetitions value used in SNMP GET-BULK requests
/// </summary>
protected int _maxRepetitions = 50;
/// <summary>
/// Flag determines if exceptions are suppressed or thrown. When exceptions are suppressed, methods
/// return null on errors regardless of what the error is.
/// </summary>
protected bool _suppressExceptions = true;
/// <summary>Constructor.</summary>
/// <remarks>
/// Class is initialized to default values. Peer IP address is set to loopback, peer port number
/// to 161, timeout to 2000 ms (2 seconds), retry count to 2 and community name to public.
/// </remarks>
public SimpleSnmp()
{
_peerIP = IPAddress.Loopback;
_peerPort = 161;
_timeout = 2000;
_retry = 2;
_community = "public";
_target = null;
_peerName = "localhost";
}
/// <summary>
/// Constructor.
/// </summary>
/// <remarks>
/// Class is initialized with default values with the agent name set to the supplied DNS name (or
/// IP address). If peer name is a DNS name, DNS resolution will take place in the constructor attempting
/// to resolve it an IP address.
/// </remarks>
/// <param name="peerName">Peer name or IP address</param>
public SimpleSnmp(string peerName)
: this()
{
_peerName = peerName;
Resolve();
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="peerName">Peer name or IP address</param>
/// <param name="community">SNMP community name</param>
public SimpleSnmp(string peerName, string community)
: this(peerName)
{
_community = community;
}
/// <summary>
/// Constructor.
/// </summary>
/// <param name="peerName">Peer name or IP address</param>
/// <param name="peerPort">Peer UDP port number</param>
/// <param name="community">SNMP community name</param>
public SimpleSnmp(string peerName, int peerPort, string community)
: this( peerName, community)
{
_peerPort = peerPort;
}
/// <summary>
/// Constructor.
/// </summary>
/// <param name="peerName">Peer name or IP address</param>
/// <param name="peerPort">Peer UDP port number</param>
/// <param name="community">SNMP community name</param>
/// <param name="timeout">SNMP request timeout</param>
/// <param name="retry">Maximum number of retries excluding the first request (0 = 1 request is sent)</param>
public SimpleSnmp(string peerName, int peerPort, string community, int timeout, int retry)
: this(peerName, peerPort, community)
{
_timeout = timeout;
_retry = retry;
}
/// <summary>Class validity flag</summary>
/// <remarks>
/// Return class validity status. If class is valid, it is ready to send requests and receive
/// replies. If false, requests to send requests will fail.
/// </remarks>
public bool Valid
{
get
{
if (_peerIP == IPAddress.None || _peerIP == IPAddress.Any)
{
return false;
}
if (_community.Length < 1 || _community.Length > 50)
{
return false;
}
return true;
}
}
/// <summary>
/// SNMP GET request
/// </summary>
/// <example>SNMP GET request:
/// <code>
/// String snmpAgent = "10.10.10.1";
/// String snmpCommunity = "public";
/// SimpleSnmp snmp = new SimpleSnmp(snmpAgent, snmpCommunity);
/// // Create a request Pdu
/// Pdu pdu = new Pdu();
/// pdu.Type = SnmpConstants.GET; // type GET
/// pdu.VbList.Add("1.3.6.1.2.1.1.1.0");
/// Dictionary<Oid, AsnType> result = snmp.GetNext(SnmpVersion.Ver1, pdu);
/// if( result == null ) {
/// Console.WriteLine("Request failed.");
/// } else {
/// foreach (KeyValuePair<Oid, AsnType> entry in result)
/// {
/// Console.WriteLine("{0} = {1}: {2}", entry.Key.ToString(), SnmpConstants.GetTypeName(entry.Value.Type),
/// entry.Value.ToString());
/// }
/// }
/// </code>
/// Will return:
/// <code>
/// 1.3.6.1.2.1.1.1.0 = OctetString: "Dual core Intel notebook"
/// </code>
/// </example>
/// <param name="version">SNMP protocol version. Acceptable values are SnmpVersion.Ver1 and SnmpVersion.Ver2</param>
/// <param name="pdu">Request Protocol Data Unit</param>
/// <returns>Result of the SNMP request in a dictionary format with Oid => AsnType values</returns>
public Dictionary<Oid, AsnType> Get(SnmpVersion version, Pdu pdu)
{
if (!Valid)
{
if (!_suppressExceptions)
{
throw new SnmpException("SimpleSnmp class is not valid.");
}
return null; // class is not fully initialized.
}
// function only works on SNMP version 1 and SNMP version 2 requests
if (version != SnmpVersion.Ver1 && version != SnmpVersion.Ver2)
{
if (!_suppressExceptions)
{
throw new SnmpInvalidVersionException("SimpleSnmp support SNMP version 1 and 2 only.");
}
return null;
}
try
{
_target = new UdpTarget(_peerIP, _peerPort, _timeout, _retry);
}
catch( Exception ex )
{
_target = null;
if (!_suppressExceptions)
{
throw ex;
}
}
if( _target == null )
{
return null;
}
try
{
AgentParameters param = new AgentParameters(version, new OctetString(_community));
SnmpPacket result = _target.Request(pdu, param);
if (result != null)
{
if (result.Pdu.ErrorStatus == 0)
{
Dictionary<Oid, AsnType> res = new Dictionary<Oid, AsnType>();
foreach (Vb v in result.Pdu.VbList)
{
if (version == SnmpVersion.Ver2 && (v.Value.Type == SnmpConstants.SMI_NOSUCHINSTANCE ||
v.Value.Type == SnmpConstants.SMI_NOSUCHOBJECT))
{
if (!res.ContainsKey(v.Oid))
{
res.Add(v.Oid, new Null());
}
else
{
res.Add(Oid.NullOid(), v.Value);
}
}
else
{
if (!res.ContainsKey(v.Oid))
{
res.Add(v.Oid, v.Value);
}
else
{
if (res[v.Oid].Type == v.Value.Type)
{
res[v.Oid] = v.Value; // update value of the existing Oid entry
}
else
{
throw new SnmpException(SnmpException.OidValueTypeChanged, String.Format("Value type changed from {0} to {1}", res[v.Oid].Type, v.Value.Type));
}
}
}
}
_target.Close();
_target = null;
return res;
}
else
{
if (!_suppressExceptions)
{
throw new SnmpErrorStatusException("Agent responded with an error", result.Pdu.ErrorStatus, result.Pdu.ErrorIndex);
}
}
}
}
catch( Exception ex )
{
if( ! _suppressExceptions )
{
_target.Close();
_target = null;
throw ex;
}
}
_target.Close();
_target = null;
return null;
}
/// <summary>
/// SNMP GET request
/// </summary>
/// <example>SNMP GET request:
/// <code>
/// String snmpAgent = "10.10.10.1";
/// String snmpCommunity = "public";
/// SimpleSnmp snmp = new SimpleSnmp(snmpAgent, snmpCommunity);
/// Dictionary<Oid, AsnType> result = snmp.GetNext(SnmpVersion.Ver1, new string[] { "1.3.6.1.2.1.1.1.0" });
/// if( result == null ) {
/// Console.WriteLine("Request failed.");
/// } else {
/// foreach (KeyValuePair<Oid, AsnType> entry in result)
/// {
/// Console.WriteLine("{0} = {1}: {2}", entry.Key.ToString(), SnmpConstants.GetTypeName(entry.Value.Type),
/// entry.Value.ToString());
/// }
/// }
/// </code>
/// Will return:
/// <code>
/// 1.3.6.1.2.1.1.1.0 = OctetString: "Dual core Intel notebook"
/// </code>
/// </example>
/// <param name="version">SNMP protocol version number. Acceptable values are SnmpVersion.Ver1 and SnmpVersion.Ver2</param>
/// <param name="oidList">List of request OIDs in string dotted decimal format.</param>
/// <returns>Result of the SNMP request in a dictionary format with Oid => AsnType values</returns>
public Dictionary<Oid, AsnType> Get(SnmpVersion version, string[] oidList)
{
if (!Valid)
{
if (!_suppressExceptions)
{
throw new SnmpException("SimpleSnmp class is not valid.");
}
return null;
}
// function only works on SNMP version 1 and SNMP version 2 requests
if (version != SnmpVersion.Ver1 && version != SnmpVersion.Ver2)
{
if (!_suppressExceptions)
{
throw new SnmpInvalidVersionException("SimpleSnmp support SNMP version 1 and 2 only.");
}
return null;
}
Pdu pdu = new Pdu(PduType.Get);
foreach (string s in oidList)
{
pdu.VbList.Add(s);
}
return Get(version, pdu);
}
/// <summary>
/// SNMP GET-NEXT request
/// </summary>
/// <example>SNMP GET-NEXT request:
/// <code>
/// String snmpAgent = "10.10.10.1";
/// String snmpCommunity = "private";
/// SimpleSnmp snmp = new SimpleSnmp(snmpAgent, snmpCommunity);
/// // Create a request Pdu
/// Pdu pdu = new Pdu();
/// pdu.Type = SnmpConstants.GETNEXT; // type GETNEXT
/// pdu.VbList.Add("1.3.6.1.2.1.1");
/// Dictionary<Oid, AsnType> result = snmp.GetNext(pdu);
/// if( result == null ) {
/// Console.WriteLine("Request failed.");
/// } else {
/// foreach (KeyValuePair<Oid, AsnType> entry in result)
/// {
/// Console.WriteLine("{0} = {1}: {2}", entry.Key.ToString(), SnmpConstants.GetTypeName(entry.Value.Type),
/// entry.Value.ToString());
/// }
/// }
/// </code>
/// Will return:
/// <code>
/// 1.3.6.1.2.1.1.1.0 = OctetString: "Dual core Intel notebook"
/// </code>
/// </example>
/// <param name="version">SNMP protocol version. Acceptable values are SnmpVersion.Ver1 and SnmpVersion.Ver2</param>
/// <param name="pdu">Request Protocol Data Unit</param>
/// <returns>Result of the SNMP request in a dictionary format with Oid => AsnType values</returns>
public Dictionary<Oid, AsnType> GetNext(SnmpVersion version, Pdu pdu)
{
if (!Valid)
{
if (!_suppressExceptions)
{
throw new SnmpException("SimpleSnmp class is not valid.");
}
return null; // class is not fully initialized.
}
// function only works on SNMP version 1 and SNMP version 2 requests
if (version != SnmpVersion.Ver1 && version != SnmpVersion.Ver2)
{
if (!_suppressExceptions)
{
throw new SnmpInvalidVersionException("SimpleSnmp support SNMP version 1 and 2 only.");
}
return null;
}
try
{
_target = new UdpTarget(_peerIP, _peerPort, _timeout, _retry);
}
catch
{
_target = null;
}
if( _target == null )
{
return null;
}
try
{
AgentParameters param = new AgentParameters(version, new OctetString(_community));
SnmpPacket result = _target.Request(pdu, param);
if (result != null)
{
if (result.Pdu.ErrorStatus == 0)
{
Dictionary<Oid, AsnType> res = new Dictionary<Oid, AsnType>();
foreach (Vb v in result.Pdu.VbList)
{
if (version == SnmpVersion.Ver2 &&
(v.Value.Type == SnmpConstants.SMI_ENDOFMIBVIEW) ||
(v.Value.Type == SnmpConstants.SMI_NOSUCHINSTANCE) ||
(v.Value.Type == SnmpConstants.SMI_NOSUCHOBJECT))
{
break;
}
if (res.ContainsKey(v.Oid))
{
if (res[v.Oid].Type != v.Value.Type)
{
throw new SnmpException(SnmpException.OidValueTypeChanged, "OID value type changed for OID: " + v.Oid.ToString());
}
else
{
res[v.Oid] = v.Value;
}
}
else
{
res.Add(v.Oid, v.Value);
}
}
_target.Close();
_target = null;
return res;
}
else
{
if( ! _suppressExceptions )
{
throw new SnmpErrorStatusException("Agent responded with an error", result.Pdu.ErrorStatus, result.Pdu.ErrorIndex);
}
}
}
}
catch( Exception ex )
{
if (!_suppressExceptions)
{
_target.Close();
_target = null;
throw ex;
}
}
_target.Close();
_target = null;
return null;
}
/// <summary>
/// SNMP GET-NEXT request
/// </summary>
/// <example>SNMP GET-NEXT request:
/// <code>
/// String snmpAgent = "10.10.10.1";
/// String snmpCommunity = "private";
/// SimpleSnmp snmp = new SimpleSnmp(snmpAgent, snmpCommunity);
/// Dictionary<Oid, AsnType> result = snmp.GetNext(SnmpVersion.Ver1, new string[] { "1.3.6.1.2.1.1" });
/// if( result == null ) {
/// Console.WriteLine("Request failed.");
/// } else {
/// foreach (KeyValuePair<Oid, AsnType> entry in result)
/// {
/// Console.WriteLine("{0} = {1}: {2}", entry.Key.ToString(), SnmpConstants.GetTypeName(entry.Value.Type),
/// entry.Value.ToString());
/// }
/// }
/// </code>
/// Will return:
/// <code>
/// 1.3.6.1.2.1.1.1.0 = OctetString: "Dual core Intel notebook"
/// </code>
/// </example>
/// <param name="version">SNMP protocol version number. Acceptable values are SnmpVersion.Ver1 and SnmpVersion.Ver2</param>
/// <param name="oidList">List of request OIDs in string dotted decimal format.</param>
/// <returns>Result of the SNMP request in a dictionary format with Oid => AsnType values</returns>
public Dictionary<Oid, AsnType> GetNext(SnmpVersion version, string[] oidList)
{
if (!Valid)
{
if (!_suppressExceptions)
{
throw new SnmpException("SimpleSnmp class is not valid.");
}
return null;
}
// function only works on SNMP version 1 and SNMP version 2 requests
if (version != SnmpVersion.Ver1 && version != SnmpVersion.Ver2)
{
if (!_suppressExceptions)
{
throw new SnmpInvalidVersionException("SimpleSnmp support SNMP version 1 and 2 only.");
}
return null;
}
Pdu pdu = new Pdu(PduType.GetNext);
foreach (string s in oidList)
{
pdu.VbList.Add(s);
}
return GetNext(version, pdu);
}
/// <summary>
/// SNMP GET-BULK request
/// </summary>
/// <remarks>
/// GetBulk request type is only available with SNMP v2c agents. SNMP v3 also supports the request itself
/// but that version of the protocol is not supported by SimpleSnmp.
///
/// GetBulk method will return a dictionary of Oid to value mapped values as returned form a
/// single GetBulk request to the agent. You can change how the request itself is made by changing the
/// SimpleSnmp.NonRepeaters and SimpleSnmp.MaxRepetitions values. SimpleSnmp properties are only used
/// when values in the parameter Pdu are set to 0.
/// </remarks>
/// <example>SNMP GET-BULK request:
/// <code>
/// String snmpAgent = "10.10.10.1";
/// String snmpCommunity = "private";
/// SimpleSnmp snmp = new SimpleSnmp(snmpAgent, snmpCommunity);
/// // Create a request Pdu
/// Pdu pdu = new Pdu();
/// pdu.Type = SnmpConstants.GETBULK; // type GETBULK
/// pdu.VbList.Add("1.3.6.1.2.1.1");
/// pdu.NonRepeaters = 0;
/// pdu.MaxRepetitions = 10;
/// Dictionary<Oid, AsnType> result = snmp.GetBulk(pdu);
/// if( result == null ) {
/// Console.WriteLine("Request failed.");
/// } else {
/// foreach (KeyValuePair<Oid, AsnType> entry in result)
/// {
/// Console.WriteLine("{0} = {1}: {2}", entry.Key.ToString(), SnmpConstants.GetTypeName(entry.Value.Type),
/// entry.Value.ToString());
/// }
/// }
/// </code>
/// Will return:
/// <code>
/// 1.3.6.1.2.1.1.1.0 = OctetString: "Dual core Intel notebook"
/// 1.3.6.1.2.1.1.2.0 = ObjectId: 1.3.6.1.9.233233.1.1
/// 1.3.6.1.2.1.1.3.0 = TimeTicks: 0d 0h 0m 1s 420ms
/// 1.3.6.1.2.1.1.4.0 = OctetString: "msinadinovic@users.sourceforge.net"
/// 1.3.6.1.2.1.1.5.0 = OctetString: "milans-nbook"
/// 1.3.6.1.2.1.1.6.0 = OctetString: "Developer home"
/// 1.3.6.1.2.1.1.8.0 = TimeTicks: 0d 0h 0m 0s 10ms
/// </code>
/// </example>
/// <param name="pdu">Request Protocol Data Unit</param>
/// <returns>Result of the SNMP request in a dictionary format with Oid => AsnType values</returns>
public Dictionary<Oid, AsnType> GetBulk(Pdu pdu)
{
if (!Valid)
{
if (!_suppressExceptions)
{
throw new SnmpException("SimpleSnmp class is not valid.");
}
return null; // class is not fully initialized.
}
try
{
pdu.NonRepeaters = _nonRepeaters;
pdu.MaxRepetitions = _maxRepetitions;
_target = new UdpTarget(_peerIP, _peerPort, _timeout, _retry);
}
catch(Exception ex)
{
_target = null;
if (!_suppressExceptions)
{
throw ex;
}
}
if( _target == null )
{
return null;
}
try
{
AgentParameters param = new AgentParameters(SnmpVersion.Ver2, new OctetString(_community));
SnmpPacket result = _target.Request(pdu, param);
if (result != null)
{
if (result.Pdu.ErrorStatus == 0)
{
Dictionary<Oid, AsnType> res = new Dictionary<Oid, AsnType>();
foreach (Vb v in result.Pdu.VbList)
{
if (
(v.Value.Type == SnmpConstants.SMI_ENDOFMIBVIEW) ||
(v.Value.Type == SnmpConstants.SMI_NOSUCHINSTANCE) ||
(v.Value.Type == SnmpConstants.SMI_NOSUCHOBJECT)
)
{
break;
}
if (res.ContainsKey(v.Oid))
{
if (res[v.Oid].Type != v.Value.Type)
{
throw new SnmpException(SnmpException.OidValueTypeChanged, "OID value type changed for OID: " + v.Oid.ToString());
}
else
{
res[v.Oid] = v.Value;
}
}
else
{
res.Add(v.Oid, v.Value);
}
}
_target.Close();
_target = null;
return res;
}
else
{
if( ! _suppressExceptions )
{
throw new SnmpErrorStatusException("Agent responded with an error", result.Pdu.ErrorStatus, result.Pdu.ErrorIndex);
}
}
}
}
catch(Exception ex)
{
if( ! _suppressExceptions )
{
_target.Close();
_target = null;
throw ex;
}
}
_target.Close();
_target = null;
return null;
}
/// <summary>
/// SNMP GET-BULK request
/// </summary>
/// <remarks>
/// Performs a GetBulk SNMP v2 operation on a list of OIDs. This is a convenience function that
/// calls GetBulk(Pdu) method.
/// </remarks>
/// <example>SNMP GET-BULK request:
/// <code>
/// String snmpAgent = "10.10.10.1";
/// String snmpCommunity = "private";
/// SimpleSnmp snmp = new SimpleSnmp(snmpAgent, snmpCommunity);
/// Dictionary<Oid, AsnType> result = snmp.GetBulk(new string[] { "1.3.6.1.2.1.1" });
/// if( result == null ) {
/// Console.WriteLine("Request failed.");
/// } else {
/// foreach (KeyValuePair<Oid, AsnType> entry in result)
/// {
/// Console.WriteLine("{0} = {1}: {2}", entry.Key.ToString(), SnmpConstants.GetTypeName(entry.Value.Type),
/// entry.Value.ToString());
/// }
/// }
/// </code>
/// </example>
/// <param name="oidList">List of request OIDs in string dotted decimal format.</param>
/// <returns>Result of the SNMP request in a dictionary format with Oid => AsnType values</returns>
public Dictionary<Oid, AsnType> GetBulk(string[] oidList)
{
if (!Valid)
{
if (!_suppressExceptions)
{
throw new SnmpException("SimpleSnmp class is not valid.");
}
return null;
}
Pdu pdu = new Pdu(PduType.GetBulk);
pdu.MaxRepetitions = _maxRepetitions;
pdu.NonRepeaters = _nonRepeaters;
foreach (string s in oidList)
{
pdu.VbList.Add(s);
}
return GetBulk(pdu);
}
/// <summary>
/// SNMP SET request
/// </summary>
/// <example>Set operation in SNMP version 1:
/// <code>
/// String snmpAgent = "10.10.10.1";
/// String snmpCommunity = "private";
/// SimpleSnmp snmp = new SimpleSnmp(snmpAgent, snmpCommunity);
/// // Create a request Pdu
/// Pdu pdu = new Pdu();
/// pdu.Type = SnmpConstants.SET; // type SET
/// Oid setOid = new Oid("1.3.6.1.2.1.1.1.0"); // sysDescr.0
/// OctetString setValue = new OctetString("My personal toy");
/// pdu.VbList.Add(setOid, setValue);
/// Dictionary<Oid, AsnType> result = snmp.Set(SnmpVersion.Ver1, pdu);
/// if( result == null ) {
/// Console.WriteLine("Request failed.");
/// } else {
/// Console.WriteLine("Success!");
/// }
/// </code>
///
/// To use SNMP version 2, change snmp.Set() method call first parameter to SnmpVersion.Ver2.
/// </example>
/// <param name="version">SNMP protocol version number. Acceptable values are SnmpVersion.Ver1 and SnmpVersion.Ver2</param>
/// <param name="pdu">Request Protocol Data Unit</param>
/// <returns>Result of the SNMP request in a dictionary format with Oid => AsnType values</returns>
public Dictionary<Oid, AsnType> Set(SnmpVersion version, Pdu pdu)
{
if (!Valid)
{
if (!_suppressExceptions)
{
throw new SnmpException("SimpleSnmp class is not valid.");
}
return null; // class is not fully initialized.
}
// function only works on SNMP version 1 and SNMP version 2 requests
if (version != SnmpVersion.Ver1 && version != SnmpVersion.Ver2)
{
if (!_suppressExceptions)
{
throw new SnmpInvalidVersionException("SimpleSnmp support SNMP version 1 and 2 only.");
}
return null;
}
try
{
_target = new UdpTarget(_peerIP, _peerPort, _timeout, _retry);
}
catch(Exception ex)
{
_target = null;
if( ! _suppressExceptions)
{
throw ex;
}
}
if( _target == null )
{
return null;
}
try {
AgentParameters param = new AgentParameters(version, new OctetString(_community));
SnmpPacket result = _target.Request(pdu, param);
if (result != null)
{
if (result.Pdu.ErrorStatus == 0)
{
Dictionary<Oid, AsnType> res = new Dictionary<Oid, AsnType>();
foreach (Vb v in result.Pdu.VbList)
{
if (res.ContainsKey(v.Oid))
{
if (res[v.Oid].Type != v.Value.Type)
{
throw new SnmpException(SnmpException.OidValueTypeChanged, "OID value type changed for OID: " + v.Oid.ToString());
}
else
{
res[v.Oid] = v.Value;
}
}
else
{
res.Add(v.Oid, v.Value);
}
}
_target.Close();
_target = null;
return res;
}
else
{
if( ! _suppressExceptions )
{
throw new SnmpErrorStatusException("Agent responded with an error", result.Pdu.ErrorStatus, result.Pdu.ErrorIndex);
}
}
}
}
catch(Exception ex)
{
if( ! _suppressExceptions )
{
_target.Close();
_target = null;
throw ex;
}
}
_target.Close();
_target = null;
return null;
}
/// <summary>
/// SNMP SET request
/// </summary>
/// <example>Set operation in SNMP version 1:
/// <code>
/// String snmpAgent = "10.10.10.1";
/// String snmpCommunity = "private";
/// SimpleSnmp snmp = new SimpleSnmp(snmpAgent, snmpCommunity);
/// // Create a request Pdu
/// List<Vb> vbList = new List<Vb>();
/// Oid setOid = new Oid("1.3.6.1.2.1.1.1.0"); // sysDescr.0
/// OctetString setValue = new OctetString("My personal toy");
/// vbList.Add(new Vb(setOid, setValue));
/// Dictionary<Oid, AsnType> result = snmp.Set(SnmpVersion.Ver1, list.ToArray());
/// if( result == null ) {
/// Console.WriteLine("Request failed.");
/// } else {
/// Console.WriteLine("Success!");
/// }
/// </code>
///
/// To use SNMP version 2, change snmp.Set() method call first parameter to SnmpVersion.Ver2.
/// </example>
/// <param name="version">SNMP protocol version number. Acceptable values are SnmpVersion.Ver1 and SnmpVersion.Ver2</param>
/// <param name="vbs">Vb array containing Oid/AsnValue pairs for the SET operation</param>
/// <returns>Result of the SNMP request in a dictionary format with Oid => AsnType values</returns>
public Dictionary<Oid, AsnType> Set(SnmpVersion version, Vb[] vbs)
{
if (!Valid)
{
if (!_suppressExceptions)
{
throw new SnmpException("SimpleSnmp class is not valid.");
}
return null;
}
// function only works on SNMP version 1 and SNMP version 2 requests
if (version != SnmpVersion.Ver1 && version != SnmpVersion.Ver2)
{
if (!_suppressExceptions)
{
throw new SnmpInvalidVersionException("SimpleSnmp support SNMP version 1 and 2 only.");
}
return null;
}
Pdu pdu = new Pdu(PduType.Set);
foreach (Vb vb in vbs)
{
pdu.VbList.Add(vb);
}
return Set(version, pdu);
}
/// <summary>SNMP WALK operation</summary>
/// <remarks>
/// When using SNMP version 1, walk is performed using GET-NEXT calls. When using SNMP version 2,
/// walk is performed using GET-BULK calls.
/// </remarks>
/// <example>Example SNMP walk operation using SNMP version 1:
/// <code>
/// String snmpAgent = "10.10.10.1";
/// String snmpCommunity = "private";
/// SimpleSnmp snmp = new SimpleSnmp(snmpAgent, snmpCommunity);
/// Dictionary<Oid, AsnType> result = snmp.Walk(SnmpVersion.Ver1, "1.3.6.1.2.1.1");
/// if( result == null ) {
/// Console.WriteLine("Request failed.");
/// } else {
/// foreach (KeyValuePair<Oid, AsnType> entry in result)
/// {
/// Console.WriteLine("{0} = {1}: {2}", entry.Key.ToString(), SnmpConstants.GetTypeName(entry.Value.Type),
/// entry.Value.ToString());
/// }
/// </code>
/// Will return:
/// <code>
/// 1.3.6.1.2.1.1.1.0 = OctetString: "Dual core Intel notebook"
/// 1.3.6.1.2.1.1.2.0 = ObjectId: 1.3.6.1.9.233233.1.1
/// 1.3.6.1.2.1.1.3.0 = TimeTicks: 0d 0h 0m 1s 420ms
/// 1.3.6.1.2.1.1.4.0 = OctetString: "msinadinovic@users.sourceforge.net"
/// 1.3.6.1.2.1.1.5.0 = OctetString: "milans-nbook"
/// 1.3.6.1.2.1.1.6.0 = OctetString: "Developer home"
/// 1.3.6.1.2.1.1.8.0 = TimeTicks: 0d 0h 0m 0s 10ms
/// </code>
///
/// To use SNMP version 2, change snmp.Set() method call first parameter to SnmpVersion.Ver2.
/// </example>
/// <param name="version">SNMP protocol version. Acceptable values are SnmpVersion.Ver1 and
/// SnmpVersion.Ver2</param>
/// <param name="rootOid">OID to start WALK operation from. Only child OIDs of the rootOid will be
/// retrieved and returned</param>
/// <returns>Oid => AsnType value mappings on success, empty dictionary if no data was found or
/// null on error</returns>
public Dictionary<Oid, AsnType> Walk(SnmpVersion version, string rootOid)
{
if (!Valid)
{
if (!_suppressExceptions)
{
throw new SnmpException("SimpleSnmp class is not valid.");
}
return null;
}
// function only works on SNMP version 1 and SNMP version 2 requests
if (version != SnmpVersion.Ver1 && version != SnmpVersion.Ver2)
{
if (!_suppressExceptions)
{
throw new SnmpInvalidVersionException("SimpleSnmp support SNMP version 1 and 2 only.");
}
return null;
}
if (rootOid.Length < 2)
{
if( ! _suppressExceptions)
{
throw new SnmpException(SnmpException.InvalidOid, "RootOid is not a valid Oid");
}
return null;
}
Oid root = new Oid(rootOid);
if (root.Length <= 0)
{
return null; // unable to parse root oid
}
Oid lastOid = (Oid)root.Clone();
Dictionary<Oid, AsnType> result = new Dictionary<Oid, AsnType>();
while (lastOid != null && root.IsRootOf(lastOid))
{
Dictionary<Oid, AsnType> val = null;
if (version == SnmpVersion.Ver1)
{
val = GetNext(version, new string[] { lastOid.ToString() });
}
else
{
val = GetBulk(new string[] { lastOid.ToString() });
}
// check that we have a result
if (val == null || val.Count == 0)
{
// error of some sort happened. abort...
break;
}
foreach (KeyValuePair<Oid, AsnType> entry in val)
{
if (root.IsRootOf(entry.Key))
{
if (result.ContainsKey(entry.Key))
{
if (result[entry.Key].Type != entry.Value.Type)
{
throw new SnmpException(SnmpException.OidValueTypeChanged, "OID value type changed for OID: " + entry.Key.ToString());
}
else
result[entry.Key] = entry.Value;
}
else
{
result.Add(entry.Key, entry.Value);
}
lastOid = (Oid)entry.Key.Clone();
}
else
{
// it's faster to check if variable is null then checking IsRootOf
lastOid = null;
break;
}
}
}