csocketssnmpnet-snmp

How to use snmpwalk in C?


I want to use snmpwalk like feature.

I want to print all the users from a given OID table, but I am only gettting the value of the first row, when I am using GETNEXT and I am getting only the second value when I am using the GETNEXTBULK.

This is the code:

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

int main() {
    oid target_oid[] = {1, 3, 6, 1, 4, 1, 89, 79, 17, 1, 1, 2, 107, 107};  
    size_t target_oid_len = OID_LENGTH(target_oid);

    init_snmp("snmpget");

    //SNMP session
    netsnmp_session session, *ss;
    snmp_sess_init(&session);
    session.peername = strdup("172.16.100.46");  
    session.version = SNMP_VERSION_2c;
    session.community = "public";
    session.community_len = strlen(session.community);

    SOCK_STARTUP;
    ss = snmp_open(&session);
    if (!ss) {
        snmp_perror("snmp_open");
        SOCK_CLEANUP;
        exit(1);
    }

    //SNMP GET request
    netsnmp_pdu *response;
    netsnmp_pdu *pdu = snmp_pdu_create(SNMP_MSG_GETBULK);
    pdu->non_repeaters = 0; pdu->max_repetitions = 15;
    snmp_add_null_var(pdu, target_oid, target_oid_len);


    int status = snmp_synch_response(ss, pdu, &response);
     
     if (status == STAT_SUCCESS && response->variables) {
        printf("%s\n", response->variables->val.string);}      
    else if (status == STAT_TIMEOUT) {
        fprintf(stderr, "SNMP Timeout\n");
    } else {
        snmp_sess_perror("snmpget", ss);
    }

    // Clean up
    if (response) {
        snmp_free_pdu(response);
    }
    snmp_close(ss);
    SOCK_CLEANUP;

    return 0;
}

Solution

  • SNMP itself does not have a "walk" operation, that's just the name that net-snmp gives to a series of successive GET-NEXT requests. In order to implement this yourself, you need to use a loop that makes a GET-NEXT request, and then uses the OID from the response in the next request.