To make a simple snmp trap application , you should parse and run snmptrapd.c to catch traps which comes from your defined port address.
Code structure is heavy for beginners to trap so i will tell you the important points of snmptrapd.c to make a simple trap receiver.
transport = netsnmp_transport_open_server("snmptrap", cp);
This line opens a server for you to listen defined port number ,"cp".
Warning: In linux os , port 162 can listen with only root user. So if you want to listen port 162 ,you should run the code with sudo.
ss = snmptrapd_add_session(transport);
You should create a netsnmp_session.
while (netsnmp_running) {
...
numfds = 0;
FD_ZERO(&readfds);
FD_ZERO(&writefds);
FD_ZERO(&exceptfds);
block = 0;
tvp = &timeout;
timerclear(tvp);
tvp->tv_sec = 5;
snmp_select_info(&numfds, &readfds, tvp, &block);
if (block == 1)
tvp = NULL; /* block without timeout */
count = select(numfds, &readfds, &writefds, &exceptfds, tvp);
if (count > 0) {
if (count > 0) {
snmp_read(&readfds);
}
} else {
switch (count) {
case 0:
snmp_timeout();
break;
case -1:
if (errno == EINTR)
continue;
netsnmp_running = 0;
break;
default:
netsnmp_running = 0;
}
}
}
Main loop for catching snmp traps at defined port.
static netsnmp_session *
snmptrapd_add_session(netsnmp_transport *t)
{
...
session->callback = snmp_input;
...
}
After all , your trap's data will be in
snmp_input
function. You can take oid , value , value type , sender ipnumber etc.
of trap.