C#简单实现SNMP的方法

本文实例讲述了C#简单实现SNMP的方法。分享给大家供大家参考。具体如下:

/**
C# Network Programming
by Richard Blum
Publisher: Sybex
ISBN: 0782141765
*/
using System;
using System.Text;
using System.Net;
using System.Net.Sockets;
public class SimpleSNMP
{
  public static void Main(string[] argv)
  {
   int commlength, miblength, datatype, datalength, datastart;
   int uptime = 0;
   string output;
   SNMP conn = new SNMP();
   byte[] response = new byte[1024];
   Console.WriteLine("Device SNMP information:");
   // Send sysName SNMP request
   response = conn.get("get", argv[0], argv[1], "1.3.6.1.2.1.1.5.0");
   if (response[0] == 0xff)
   {
     Console.WriteLine("No response from {0}", argv[0]);
     return;
   }
   // If response, get the community name and MIB lengths
   commlength = Convert.ToInt16(response[6]);
   miblength = Convert.ToInt16(response[23 + commlength]);
   // Extract the MIB data from the SNMP response
   datatype = Convert.ToInt16(response[24 + commlength + miblength]);
   datalength = Convert.ToInt16(response[25 + commlength + miblength]);
   datastart = 26 + commlength + miblength;
   output = Encoding.ASCII.GetString(response, datastart, datalength);
   Console.WriteLine(" sysName - Datatype: {0}, Value: {1}",
       datatype, output);
   // Send a sysLocation SNMP request
   response = conn.get("get", argv[0], argv[1], "1.3.6.1.2.1.1.6.0");
   if (response[0] == 0xff)
   {
     Console.WriteLine("No response from {0}", argv[0]);
     return;
   }
   // If response, get the community name and MIB lengths
   commlength = Convert.ToInt16(response[6]);
   miblength = Convert.ToInt16(response[23 + commlength]);
   // Extract the MIB data from the SNMP response
   datatype = Convert.ToInt16(response[24 + commlength + miblength]);
   datalength = Convert.ToInt16(response[25 + commlength + miblength]);
   datastart = 26 + commlength + miblength;
   output = Encoding.ASCII.GetString(response, datastart, datalength);
   Console.WriteLine(" sysLocation - Datatype: {0}, Value: {1}", datatype, output);
   // Send a sysContact SNMP request
   response = conn.get("get", argv[0], argv[1], "1.3.6.1.2.1.1.4.0");
   if (response[0] == 0xff)
   {
     Console.WriteLine("No response from {0}", argv[0]);
     return;
   }
   // Get the community and MIB lengths
   commlength = Convert.ToInt16(response[6]);
   miblength = Convert.ToInt16(response[23 + commlength]);
   // Extract the MIB data from the SNMP response
   datatype = Convert.ToInt16(response[24 + commlength + miblength]);
   datalength = Convert.ToInt16(response[25 + commlength + miblength]);
   datastart = 26 + commlength + miblength;
   output = Encoding.ASCII.GetString(response, datastart, datalength);
   Console.WriteLine(" sysContact - Datatype: {0}, Value: {1}",
       datatype, output);
   // Send a SysUptime SNMP request
   response = conn.get("get", argv[0], argv[1], "1.3.6.1.2.1.1.3.0");
   if (response[0] == 0xff)
   {
     Console.WriteLine("No response from {0}", argv[0]);
     return;
   }
   // Get the community and MIB lengths of the response
   commlength = Convert.ToInt16(response[6]);
   miblength = Convert.ToInt16(response[23 + commlength]);
   // Extract the MIB data from the SNMp response
   datatype = Convert.ToInt16(response[24 + commlength + miblength]);
   datalength = Convert.ToInt16(response[25 + commlength + miblength]);
   datastart = 26 + commlength + miblength;
   // The sysUptime value may by a multi-byte integer
   // Each byte read must be shifted to the higher byte order
   while(datalength > 0)
   {
     uptime = (uptime << 8) + response[datastart++];
     datalength--;
   }
   Console.WriteLine(" sysUptime - Datatype: {0}, Value: {1}",
       datatype, uptime);
  }
}
class SNMP
{
  public SNMP()
  {
  }
  public byte[] get(string request, string host, string community, string mibstring)
  {
   byte[] packet = new byte[1024];
   byte[] mib = new byte[1024];
   int snmplen;
   int comlen = community.Length;
   string[] mibvals = mibstring.Split('.');
   int miblen = mibvals.Length;
   int cnt = 0, temp, i;
   int orgmiblen = miblen;
   int pos = 0;
   // Convert the string MIB into a byte array of integer values
   // Unfortunately, values over 128 require multiple bytes
   // which also increases the MIB length
   for (i = 0; i < orgmiblen; i++)
   {
     temp = Convert.ToInt16(mibvals[i]);
     if (temp > 127)
     {
      mib[cnt] = Convert.ToByte(128 + (temp / 128));
      mib[cnt + 1] = Convert.ToByte(temp - ((temp / 128) * 128));
      cnt += 2;
      miblen++;
     } else
     {
      mib[cnt] = Convert.ToByte(temp);
      cnt++;
     }
   }
   snmplen = 29 + comlen + miblen - 1; //Length of entire SNMP packet
   //The SNMP sequence start
   packet[pos++] = 0x30; //Sequence start
   packet[pos++] = Convert.ToByte(snmplen - 2); //sequence size
   //SNMP version
   packet[pos++] = 0x02; //Integer type
   packet[pos++] = 0x01; //length
   packet[pos++] = 0x00; //SNMP version 1
   //Community name
   packet[pos++] = 0x04; // String type
   packet[pos++] = Convert.ToByte(comlen); //length
   //Convert community name to byte array
   byte[] data = Encoding.ASCII.GetBytes(community);
   for (i = 0; i < data.Length; i++)
   {
     packet[pos++] = data[i];
   }
   //Add GetRequest or GetNextRequest value
   if (request == "get")
     packet[pos++] = 0xA0;
   else
     packet[pos++] = 0xA1;
   packet[pos++] = Convert.ToByte(20 + miblen - 1); //Size of total MIB
   //Request ID
   packet[pos++] = 0x02; //Integer type
   packet[pos++] = 0x04; //length
   packet[pos++] = 0x00; //SNMP request ID
   packet[pos++] = 0x00;
   packet[pos++] = 0x00;
   packet[pos++] = 0x01;
   //Error status
   packet[pos++] = 0x02; //Integer type
   packet[pos++] = 0x01; //length
   packet[pos++] = 0x00; //SNMP error status
   //Error index
   packet[pos++] = 0x02; //Integer type
   packet[pos++] = 0x01; //length
   packet[pos++] = 0x00; //SNMP error index
   //Start of variable bindings
   packet[pos++] = 0x30; //Start of variable bindings sequence
   packet[pos++] = Convert.ToByte(6 + miblen - 1); // Size of variable binding
   packet[pos++] = 0x30; //Start of first variable bindings sequence
   packet[pos++] = Convert.ToByte(6 + miblen - 1 - 2); // size
   packet[pos++] = 0x06; //Object type
   packet[pos++] = Convert.ToByte(miblen - 1); //length
   //Start of MIB
   packet[pos++] = 0x2b;
   //Place MIB array in packet
   for(i = 2; i < miblen; i++)
     packet[pos++] = Convert.ToByte(mib[i]);
   packet[pos++] = 0x05; //Null object value
   packet[pos++] = 0x00; //Null
   //Send packet to destination
   Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram,
            ProtocolType.Udp);
   sock.SetSocketOption(SocketOptionLevel.Socket,
           SocketOptionName.ReceiveTimeout, 5000);
   IPHostEntry ihe = Dns.Resolve(host);
   IPEndPoint iep = new IPEndPoint(ihe.AddressList[0], 161);
   EndPoint ep = (EndPoint)iep;
   sock.SendTo(packet, snmplen, SocketFlags.None, iep);
   //Receive response from packet
   try
   {
     int recv = sock.ReceiveFrom(packet, ref ep);
   } catch (SocketException)
   {
     packet[0] = 0xff;
   }
   return packet;
  }
  public string getnextMIB(byte[] mibin)
  {
   string output = "1.3";
   int commlength = mibin[6];
   int mibstart = 6 + commlength + 17; //find the start of the mib section
   //The MIB length is the length defined in the SNMP packet
   // minus 1 to remove the ending .0, which is not used
   int miblength = mibin[mibstart] - 1;
   mibstart += 2; //skip over the length and 0x2b values
   int mibvalue;
   for(int i = mibstart; i < mibstart + miblength; i++)
   {
     mibvalue = Convert.ToInt16(mibin[i]);
     if (mibvalue > 128)
     {
      mibvalue = (mibvalue/128)*128 + Convert.ToInt16(mibin[i+1]);
      //ERROR here, it should be mibvalue = (mibvalue-128)*128 + Convert.ToInt16(mibin[i+1]);
      //for mib values greater than 128, the math is not adding up correctly
      i++;
     }
     output += "." + mibvalue;
   }
   return output;
  }
}

希望本文所述对大家的C#程序设计有所帮助。

(0)

相关推荐

  • C#实现TCP连接信息统计的方法

    本文实例讲述了C#实现TCP连接信息统计的方法.分享给大家供大家参考.具体实现方法如下: using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Net.Netw

  • C#实现Zip压缩目录中所有文件的方法

    本文实例讲述了C#实现Zip压缩目录中所有文件的方法.分享给大家供大家参考.具体实现方法如下: using System; using System.IO; using System.Collections; using System.IO.Compression; using System.Collections.Generic; class FolderZip { private const long BUFFER_SIZE = 20480; static void main(string[

  • C#使用默认浏览器打开网页的方法

    本文实例讲述了C#使用默认浏览器打开网页的方法.分享给大家供大家参考.具体实现方法如下: public static bool OpenBrowser(String url) { RegistryKey key = Registry.ClassesRoot.OpenSubKey(@"http\shell\open\command\"); String s = key.GetValue("").ToString(); String browserpath = null

  • C#实现根据银行卡卡号判断银行名

    原文是 java ,现在将它翻译成 C# ,并对代码重新编排整理,博主是一个今年刚出来的应届毕业生,不足之处请多多包涵. 根据银行卡号判断所属银行,依据是卡号的前6位数,称之为bin号. 我们把bin号转化为长整形,再把各个银行卡的bin号做成有序表.通过二分查找的方法,找到bin号在有序表的位置,然后读出银行卡的信息. 测试发现部分新卡号未能识别. 1.创建项目:BankInfoDemo(控制台应用程序) 2.新建类:BankInfo.cs 详细内容见附件 3.修改类:Program.cs c

  • C#实现按数据库邮件列表发送邮件的方法

    本文实例讲述了C#实现按数据库邮件列表发送邮件的方法.分享给大家供大家参考.具体实现方法如下: using System; using System.Net; using System.Net.Mail; using System.Text; using System.Threading; delegate void sendDelegate(string from, string to, string subject, string body, string host, int port, s

  • C#实现多线程的Web代理服务器实例

    本文实例讲述了C#实现多线程的Web代理服务器.分享给大家供大家参考.具体如下: /** Proxy.cs: C# Programming Tips & Techniques by Charles Wright, Kris Jamsa Publisher: Osborne/McGraw-Hill (December 28, 2001) ISBN: 0072193794 */ // Proxy.cs -- Implements a multi-threaded Web proxy server /

  • C#实现基于IE内核的简单浏览器完整实例

    本文实例讲述了C#实现基于IE内核的简单浏览器.分享给大家供大家参考.具体如下: Form1.cs如下: using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace Kit

  • C#简单实现SNMP的方法

    本文实例讲述了C#简单实现SNMP的方法.分享给大家供大家参考.具体如下: /** C# Network Programming by Richard Blum Publisher: Sybex ISBN: 0782141765 */ using System; using System.Text; using System.Net; using System.Net.Sockets; public class SimpleSNMP { public static void Main(strin

  • php简单复制文件的方法

    本文实例讲述了php简单复制文件的方法.分享给大家供大家参考,具体如下: <?php /** *author:果冻 *qq:52091199 *wyg517.blog.163.com **/ $file = 'image/a1.jpg'; $newfile = 'a/123.jpg'; //必须有写入权限 if (file_exists($file) == false) { die ('文件不在,无法复制'); } $result = copy($file, $newfile); if ($re

  • Python使用shelve模块实现简单数据存储的方法

    本文实例讲述了Python使用shelve模块实现简单数据存储的方法.分享给大家供大家参考.具体分析如下: Python的shelve模块提供了一种简单的数据存储方案,以dict(字典)的形式来操作数据. #!/usr/bin/python import sys, shelve def store_person(db): """ Query user for data and store it in the shelf object """ pi

  • python根据出生年份简单计算生肖的方法

    本文实例讲述了python根据出生年份简单计算生肖的方法.分享给大家供大家参考.具体分析如下: 这里使用python根据出生年份计算生肖,看了代码会发现原来这么简单 #计算生肖 def ChineseZodiac(year): return u'猴鸡狗猪鼠牛虎兔龙蛇马羊'[year%12] ChineseZodiac(1990) 希望本文所述对大家的Python程序设计有所帮助.

  • jQuery简单创建节点的方法

    本文实例讲述了jQuery简单创建节点的方法.分享给大家供大家参考,具体如下: <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title></title> <script type="text/javascript" src="js/jquery-1

  • GO语言实现简单TCP服务的方法

    本文实例讲述了GO语言实现简单TCP服务的方法.分享给大家供大家参考.具体实现方法如下: 复制代码 代码如下: package main import ( "net" "fmt" ) var (   maxRead = 1100     msgStop   = []byte("cmdStop")     msgStart  = []byte("cmdContinue")     ) func main() {       ho

  • JS+CSS简单树形菜单实现方法

    本文实例讲述了JS+CSS简单树形菜单实现方法.分享给大家供大家参考.具体如下: 这是一款不错的CSS树形菜单,树状列表,当然不全是CSS实现,部分功能还使用了JavaScript代码进行配合,删减了修饰用的菜单图片,大家用的时候自己图片加进去,IMG标签大部分都预留了出来,稍懂Html语法的朋友很容易就看懂的. 运行效果截图如下: 在线演示地址如下: http://demo.jb51.net/js/2015/js-css-simple-tree-menu-style-codes/ 具体代码如下

  • JS实现简单路由器功能的方法

    本文实例讲述了JS实现简单路由器功能的方法.分享给大家供大家参考.具体实现方法如下: var wawa = {}; wawa.Router = function(){ function Router(){ } Router.prototype.setup = function(routemap, defaultFunc){ var that = this, rule, func; this.routemap = []; this.defaultFunc = defaultFunc; for (v

  • 一个极为简单的requirejs实现方法

    require和 sea的源码分析,我之前的博客有写过, 今天我想分享的是一个很简单的核心代码(不带注释和空行大概60行), 没有容错判断. require.js require函数实现用一句话概括: 依次加载require的模块,然后监测script的onload事件,判断所有模块加载成功,执行require的callback, 如果只带一个参数且不是数组,就是加载成功后return 模块. //标记已经加载成功的个数 var REQ_TOTAL = 0; //模块导出 window.expo

  • 关于RequireJS的简单介绍即使用方法

    RequireJS介绍 RequireJS 是一个JavaScript模块加载器.它非常适合在浏览器中使用.使用RequireJS加载模块化脚本将提高代码的加载速度和质量. 兼容性 浏览器(browser) 是否兼容 IE 6+ 兼容 ✔ Firefox 2+ 兼容 ✔ Safari 3.2+ 兼容 ✔ Chrome 3+ 兼容 ✔ Opera 10+ 兼容 ✔ 优点 实现js文件的异步加载,避免网页失去响应 管理模块之间的依赖性,便于代码的编写和维护 快速上手 step 1 引入require

随机推荐