Example: Running a SNMP query


Overview

In this example I show you how to create a simple SNMP query program using the library types rssnmp_device_t, rssnmp_varbind_t, rssnmp_query_t and rssnmp_result_t. I chose here to make a BULK request (or bulk walk if you wish) on the ifDescr branch of the IF-MIB, to fetch a interface name list.


Code

Ok, let's start by writing the includes and declaring variables.


#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>

#include <rssnmp/snmp.h>
#include <rssnmp/query.h>


int main(int argc, char **argv)
{
  rssnmp_oid_t ifDescr[] = {1,3,6,1,2,1,2,2,1,2};
  rssnmp_device_t dev;
  rssnmp_query_t query;
  rssnmp_result_t res;
  rssnmp_varbind_t var;
  char tmp1[1024], tmp2[1024];
  int sockfd;
	

We instanced the OID 1.3.6.1.2.1.2.2.1.2 that represents the ifDescr. Now we proceed to initialize the UDP socket:


  if ( (sockfd = socket(AF_INET, SOCK_DGRAM, 0)) == -1) {
    perror("socket");
    exit(1);
  }
	
Once the socket is initialized, let us create the device and query:

  dev = rssnmp_device_New("127.0.0.1",       // host
                          161,               // port
			  SNMP_VERSION_2c,   // SNMP version
			  "foobar");         // SNMP community
  query = rssnmp_query_New(dev, RSSNMP_QUERY_TYPE_BULK);
  rssnmp_query_AddVariable(query, ifDescr, 
                           sizeof(ifDescr)/sizeof(rssnmp_oid_t));
	

So we are sending the query to localhost, to the default SNMP port (161), using SNMP version 2c and the agent community is "foobar". Then we create the BULK query and tie it to the device we just created. Finally, we set the variable of interest. It seems that we are all set to execute the query:


  res = rssnmp_query_Exec(query, sockfd);
  if (!res) {
    fprintf(stderr, "Query failed.");
    exit(1);
  }
	

If everything went fine, you can now print the results:


  while ( (var = rssnmp_result_GetNextVariable(res)) )
    printf("%s: %s\n",
	   rssnmp_varbind_GetOidText(var, tmp1, 1024),
	   rssnmp_varbind_GetValue(var, tmp2, 1024));
  
  return 0;
}
	

Program output


1.3.6.1.2.1.2.2.1.2.1: lo
1.3.6.1.2.1.2.2.1.2.2: eth0
1.3.6.1.2.1.2.2.1.2.3: sit0