1. 程式人生 > >Visual C# 2015調用SnmpSharpNet庫實現簡單的SNMP元素查詢

Visual C# 2015調用SnmpSharpNet庫實現簡單的SNMP元素查詢

msd unity because 研發 erro 發送 efi rar 如何

一開始調研發現有幾個SNMP的庫,

一個是net-SNMP,這個好像是linux用的多

一個是微軟自己的WinSNMP,這個沒有例子,不太好操作

一個是SnmpSharpNet,這個有些例子比較好,

利用SnmpSharpNet的例子實現讀取udpindatagrams的代碼如下:

要將SnmpSharpNet.dll放入Visual C# 2015的工程目錄下,然後,在工程瀏覽器的引用裏添加這個dll,方法見這裏,引用,右鍵,添加引用,瀏覽到dll即可

技術分享

 1 using System;
 2 using System.Net;
 3 using SnmpSharpNet;
4 5 namespace snmpget 6 { 7 class Program 8 { 9 static void Main(string[] args) 10 { 11 // SNMP community name 12 OctetString community = new OctetString("public"); 13 14 // Define agent parameters class 15 AgentParameters param = new
AgentParameters(community); 16 // Set SNMP version to 1 (or 2) 17 param.Version = SnmpVersion.Ver1; 18 // Construct the agent address object 19 // IpAddress class is easy to use here because 20 // it will try to resolve constructor parameter if it doesn‘t
21 // parse to an IP address 22 IpAddress agent = new IpAddress("192.168.0.10"); 23 24 // Construct target 25 UdpTarget target = new UdpTarget((IPAddress)agent, 161, 2000, 1); 26 27 // Pdu class used for all requests 28 Pdu pdu = new Pdu(PduType.Get); 29 pdu.VbList.Add("1.3.6.1.2.1.7.1.0"); //udpindatagrams 30 31 // Make SNMP request 32 SnmpV1Packet result = (SnmpV1Packet)target.Request(pdu, param); 33 34 // If result is null then agent didn‘t reply or we couldn‘t parse the reply. 35 if (result != null) 36 { 37 // ErrorStatus other then 0 is an error returned by 38 // the Agent - see SnmpConstants for error definitions 39 if (result.Pdu.ErrorStatus != 0) 40 { 41 // agent reported an error with the request 42 Console.WriteLine("Error in SNMP reply. Error {0} index {1}", 43 result.Pdu.ErrorStatus, 44 result.Pdu.ErrorIndex); 45 } 46 else 47 { 48 // Reply variables are returned in the same order as they were added 49 // to the VbList 50 Console.WriteLine("sysDescr({0}) ({1}): {2}", 51 result.Pdu.VbList[0].Oid.ToString(), 52 SnmpConstants.GetTypeName(result.Pdu.VbList[0].Value.Type), 53 result.Pdu.VbList[0].Value.ToString()); 54 } 55 } 56 else 57 { 58 Console.WriteLine("No response received from SNMP agent."); 59 } 60 target.Close(); 61 } 62 } 63 }

輸出結果如下:

技術分享

發送和接收的包的wireshark截圖:

get-request

技術分享

get-response

技術分享

接下來,需要看如何獲取網絡拓撲。。。

Visual C# 2015調用SnmpSharpNet庫實現簡單的SNMP元素查詢