4

I am trying to write a very small SNMP trap receiver, listening to UDP port 162.

Traps come in fine, but I can not decode them.

I have found libber, but it can't decode the traps for some reason. I am probably using it wrong. I imagine decoding an SNMP trap should be fairly simple and that I am missing something crucial. Is it possible to use NET-SNMP as a library and create a small trap-receiving program from it? I would not be surprised at all, but can not find any information about it. Maybe my google-fu is weak.

Prof. Falken
  • 24,226
  • 19
  • 100
  • 173
  • Come and check my code: http://stackoverflow.com/questions/38484287/how-to-decode-the-result-of-listenning-to-port-162-snmp-trap/38495948#38495948 – Tarik Aug 03 '16 at 00:03

2 Answers2

4

Well, using net-snmp, you usually use snmptrapd daemon that calls for you external commands/scripts. If you cannot use this way, I suggest you look at snmptrapd.c code. Moreover, if I recall correctly, they build a libsnmptrapd library. It should be easy to find the right API calls ...

If I have time I will update my answer with a snippet ...

my2c

neuro
  • 14,948
  • 3
  • 36
  • 59
3

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.