使用net-snmp做自己的agent

来源:互联网 发布:软件开发关键技术 编辑:程序博客网 时间:2024/06/04 19:18

参见http://net-snmp.sourceforge.net/tutorial/tutorial-4/agent/04-basic-code.html

 

1. 注册mib

 

REGISTER_MIB( "example",  example_variables, variable2,example_variables_oid );
参数分别为:

"example" : 注册的mib module的名称

example_variables: 相关的变量(之后详述)

variable2: 是example_variables的类型

example_variables_oid : 这个module的root OID

 

2. 设置 相关变量

struct variable2 example_variables[] = {
{ EXAMPLESTRING, ASN_OCTET_STR, RONLY, var_example, 1, {1}}

  };
各个分量的注释:

  • a magic number (the #defined integer constant described earlier)  这个magic就是用在routine里面,switch (vp->magic)用的
  • a type indicator (from the values listed in <snmplib/snmp_impl.h>)
  • an access indicator (essentially RWRITE or RONLY)
  • the name of the routine used to handle this entry,真正处理请求的地方
  • the length of the OID suffix used, and
  • an array of integers specifying this suffix (more on this in a moment) 表示sufix是什么
  • 像上面这个例子, {1}, 就表示了 这个的oid就是  example_variables_oid,1

     

     

    3. routine 处理请求的地方

    unsigned char *
    var_example(struct variable *vp,
                oid     *name,
                size_t  *length,
                int     exact,
                size_t  *var_len,
                WriteMethod **set_method)

     

    Four of these parameters are used for passing in information about the request, these being: 四个参数是传进来的

    struct variable *vp;// The entry in the variableN array from the//   header file, for the object under consideration.// Note that the name field of this structure has been//   completed into a fully qualified OID, by prepending//   the prefix common to the whole array.oid *name;// The OID from the requestint *length;// The length of this OIDint exact;// A flag to indicate whether this is an exact// request (GET/SET) or an 'inexact' one (GETNEXT)

    Four of the parameters are used to return information about the answer. The function also returns a pointer to the actual data for the variable requested (or NULL if this data is not available for any reason). The other result parameters are: 四个参数是传出去的

    oid *name;// The OID being returnedint *length;// The length of this OIDint *var_len;// The length of the answer being returnedWriteMethod **write_method;// A pointer to the SET function for this variable

     

    这个函数进入后,先要判断这次的oid是否在范围之内。如果是get-next就要对oid做相应的处理。

     

    vp->magic表示了实际要获取的位置。 最后根据这个magic值返回response

    例如

     

      switch(vp->magic) {


        case IFNAME:

            if ( strlen(ifXEntry.ifName) > IFNAME_DISPLAY_STRING_LEN)
                  *var_len = IFNAME_DISPLAY_STRING_LEN;
            else
                  *var_len = strlen(ifXEntry.ifName);
            return (unsigned char *) ifXEntry.ifName;
            break;
        default:
          ERROR_MSG("");
      }

    原创粉丝点击