I have a the following configurations:
How can I send traps using C or C++ and net-snmp module in linux? I need a sample code. All sample codes at net-snmp site did not work for me.
my sample code:
#include <net-snmp/net-snmp-config.h>
#include <net-snmp/net-snmp-includes.h>
oid objid_id[] = { 1,3,6,1,4,1,78945,1,1,2,4,0};
oid objid_name[] = { 1,3,6,1,4,1,78945,1,1,2,1,0};
oid trap_oid[] = {1,3,6,1,4,1,78945,1,1,1,1,1};
int main()
{
netsnmp_session session, *ss;
netsnmp_pdu *pdu, *response;
char comm[] = "public";
snmp_sess_init( &session );
session.version = SNMP_VERSION_2c;
session.community = comm;
session.community_len = strlen(session.community);
session.peername = "192.168.4.10:1234";
ss = snmp_open(&session);
if (!ss) {
snmp_sess_perror("ack", &session);
exit(1);
}
pdu = snmp_pdu_create(SNMP_MSG_TRAP2);
pdu->community = comm;
pdu->community_len = strlen(comm);
pdu->enterprise = trap_oid;
pdu->enterprise_length = sizeof(trap_oid) / sizeof(oid);
pdu->trap_type = SNMP_TRAP_ENTERPRISESPECIFIC;
snmp_add_var(pdu, objid_name, sizeof(objid_name) / sizeof(oid), 's', "Test Name");
snmp_add_var(pdu, objid_id, sizeof(objid_id) / sizeof(oid), 'i', "5468");
send_trap_to_sess (ss, pdu);
snmp_close(ss);
return (0);
}
The heartbeat notification example from net-snmp site confused me with where to give the listener details?
Thank you in advance.
It looks like system uptime and trap oid are to be added as first variables in the pdu.
The following code did the trick:
#include <net-snmp/net-snmp-config.h>
#include <net-snmp/net-snmp-includes.h>
oid objid_sysuptime[] = { 1, 3, 6, 1, 2, 1, 1, 3, 0 };
oid objid_id[] = { 1,3,6,1,4,1,78945,1,1,2,4,0};
oid objid_name[] = { 1,3,6,1,4,1,78945,1,1,2,1,0};
oid trap_oid[] = {1,3,6,1,4,1,78945,1,1,1,1,1};
int main()
{
netsnmp_session session, *ss;
netsnmp_pdu *pdu, *response;
char *trap = NULL;
char comm[] = "public";
snmp_sess_init( &session );
session.version = SNMP_VERSION_2c;
session.community = comm;
session.community_len = strlen(session.community);
session.peername = "192.168.4.10:1234";
ss = snmp_open(&session);
if (!ss) {
snmp_sess_perror("ack", &session);
exit(1);
}
pdu = snmp_pdu_create(SNMP_MSG_TRAP2);
pdu->community = comm;
pdu->community_len = strlen(comm);
pdu->trap_type = SNMP_TRAP_ENTERPRISESPECIFIC;
long sysuptime;
char csysuptime [20];
sysuptime = get_uptime ();
sprintf (csysuptime, "%ld", sysuptime);
trap = csysuptime;
snmp_add_var (pdu, objid_sysuptime, sizeof (objid_sysuptime)/sizeof(oid),'t', trap);
snmp_add_var(pdu, trap_oid, OID_LENGTH(trap_oid), 'o', "1.3.6.1.4.1.78945.1.1.1.1.1");
snmp_add_var(pdu, objid_name, OID_LENGTH(objid_name), 's', "Test Name");
snmp_add_var(pdu, objid_id, OID_LENGTH(objid_id) , 'i', "5468");
send_trap_to_sess (ss, pdu);
snmp_close(ss);
return (0);
}