在C中使用Net-SNMP的简单snmp陷阱生成器程序?

时间:2012-11-26 20:26:29

标签: c snmp net-snmp

我正在尝试创建一个简单的SNMP陷阱生成器程序,以便我可以更好地理解Net-SNMP库。使用以下代码我不断收到错误

  

snmptrap:找到配置数据但传输不能   构造

     

会话没有打开

#include <net-snmp/net-snmp-config.h>
#include <net-snmp/net-snmp-includes.h>
#include <net-snmp/agent/net-snmp-agent-includes.h>

#include "snmptrap_simple.h"

int main (int argc, char **argv) {
  oid             objid_enterprise[] = { 1, 3, 6, 1, 4, 1, 3, 1, 1 };
  oid             objid_sysdescr[] = { 1, 3, 6, 1, 2, 1, 1, 1, 0 };
  oid             objid_sysuptime[] = { 1, 3, 6, 1, 2, 1, 1, 3, 0 };
  oid             objid_snmptrap[] = { 1, 3, 6, 1, 6, 3, 1, 1, 4, 1, 0 };

  netsnmp_session session, *ss;
  netsnmp_pdu    *pdu, *response;
  oid             name[MAX_OID_LEN];
  size_t          name_length;
  int             arg;
  int             status;
  char           *trap = NULL;
  char           *prognam;
  int             exitval = 0;

  session.version       = SNMP_VERSION_1;
  session.retries       = 2;
  char address[]        = "127.0.0.1";
  char *ptrAddress      = address;
  session.peername      = ptrAddress;
  u_char comm[]         = "public";
  const u_char *community = comm;
  session.community     = community;
  session.community_len = strlen(session.community);

  /* windows32 specific initialization (is a noop on unix) */
  SOCK_STARTUP;
  // open snmp session
  ss = snmp_open(&session);
  if (!ss) {
    snmp_perror("ack");
    snmp_sess_perror("snmptrap", &session);
    snmp_log(LOG_DEBUG, "Session did not open\n");
    exit(2);
  }
  snmp_log(LOG_DEBUG, "DEBUG OUTPUT");
  // create the PDU
  pdu = snmp_pdu_create(SNMP_MSG_TRAP);
  if ( !pdu ) {
      fprintf(stderr, "Failed to create trap PDU\n");
      SOCK_CLEANUP;
      exit(1);
  }

  // add variables to the PDU
  char *value;
  *value = '42';
  if(snmp_add_var (pdu, name, name_length, 'i', value)){
    //void snmp_perror(const char *prog_string)
    snmp_perror("add variable");
    SOCK_CLEANUP;
    exit(1);
  };

  send_trap_to_sess (&session, pdu);

  return 0;
}

我做错了什么?

我在这里有代码的github回购:https://github.com/EhevuTov/tcp2snmp/blob/master/test/snmptrap_simple.c

2 个答案:

答案 0 :(得分:1)

您可能只需要在init_snmp("snmptrap_simple");之前的代码顶部调用snmp_open()

答案 1 :(得分:0)

你需要使用这个

snmp_sess_init(&ss);