标题: Net-SNMP Single API use [打印本页] 作者: saviour_q 时间: 2006-05-03 02:14 标题: Net-SNMP Single API use Author: Tony Qian
Date: May 1st, 2006
Contact: tonyqian@gmail.com
Net-SNMP provide traditional API usage and Single API Usage, however their example online only provide tradition usage, thereby I change the code a little to make it a single api usage.
The advantage for single api use is thread-safe.
You can enable mutiple thread for get set and query.
In this example I use asynchr sending with select and call back support . This is the original post and please mention the original when you post anywhere else
Here is the command to compile
gcc -I/usr/local/include -g -c -o snmp1.o snmp1.c
gcc -o snmp1 snmp1.o -L/usr/local/lib -lm -lnetsnmp -lssl -lcrypto
Here is the code
#include <net-snmp/net-snmp-config.h>
#include <net-snmp/net-snmp-includes.h>
if (operation == NETSNMP_CALLBACK_OP_RECEIVED_MESSAGE) {
if (print_result(STAT_SUCCESS, sess, pdu)) {
}
}else{
print_result(STAT_TIMEOUT, sess, pdu);
}
/* something went wrong (or end of variables)
* this host not active any more
*/
active_hosts--;
return 1;
}
int main(int argc, char **argv)
{
int liberr, syserr;
char *errstr;
void *sessp; /* <-- an opaque pointer, not a struct pointer */
struct snmp_session Session;
struct snmp_session *sptr;
struct snmp_pdu *pdu;
oid anOID[MAX_OID_LEN];
size_t anOID_len = MAX_OID_LEN;
//struct variable_list *vars;
/*
* Initialize the SNMP library
*/
init_snmp("snmputil");
/*
* Initialize a "session" defines who we're going to talk to
*/
snmp_sess_init(&Session);
Session.peername = strdup("10.255.51.2");
Session.version = SNMP_VERSION_2c;
Session.callback = asynch_response;
//Session.callback_magic = sptr;
Session.community = strdup("public");
//Session.community_len = strlen(Session.community);
sessp = snmp_sess_open(&Session);
if (sessp == NULL) {
/* Error codes found in open calling argument */
snmp_error(&Session, &liberr, &syserr, &errstr);
printf("SNMP create error %s.\n", errstr);
free(errstr);
return 0;
}
sptr = snmp_sess_session(sessp); /* <-- get the snmp_session pointer */
/* Pass sptr to snmp_sess_error from here forward */
/* Change the community name */
//printf("TEST:%s\n",sptr->peername);
free(sptr->community);
sptr->community = strdup("public");
sptr->community_len = strlen("public");
sptr->callback_magic = sptr;
/*
* Create the PDU for the data for our request.
* 1) We're going to GET the system.sysDescr.0 node.
*/
pdu = snmp_pdu_create(SNMP_MSG_GET);
read_objid(".1.3.6.1.2.1.1.1.0", anOID, &anOID_len);