I'm currently writing an asynchronous application in C but despite the examples on the web site I still get the error:
snmp_send: Bad version specified
Here is the code:
/* initialize library */
init_snmp("scanagent");
SOCK_STARTUP;
struct snmp_session *session;
struct snmp_pdu *pdu;
oid anOID[MAX_OID_LEN];
size_t anOID_len = MAX_OID_LEN;
char *peer_ip = malloc(sizeof(char) * (strlen(pool->prefix) + 5));
if(peer_ip != NULL){
/* PDU creation */
pdu = snmp_pdu_create(SNMP_MSG_GETNEXT);
if (!snmp_parse_oid(".1.3.6.1.2.1.1.1.0", anOID, &anOID_len)) {
snmp_perror(".1.3.6.1.2.1.1.1.0");
SOCK_CLEANUP;
exit(1);
}
snmp_add_null_var(pdu, anOID, anOID_len);
/* startup all hosts */
int i;
for (i = pool->start_ip; i <= pool->length; ++i) {
/* Check the next ip */
char ip[3];
sprintf(ip, ".%d", i);
strcpy(peer_ip, pool->prefix);
strcat(peer_ip, ip);
int j;
for (j = 0; j < pool->snmp_length; ++j) {
struct snmp_session sess;
snmp_info *info = pool->info[j]; /* Get the information */
char *protocol_ip = malloc(sizeof(char) * (strlen(peer_ip) + 5));
strcpy(protocol_ip, peer_ip);
strcat(protocol_ip, ":");
strcat(protocol_ip, info->port);
snmp_sess_init(&sess);
sess.peername = strdup(protocol_ip);
sess.callback = asynch_response; /* default callback */
sess.callback_magic = session;
switch(info->SNMPv) {
case 1:
set_snmp_v1(info, &sess);
break;
case 2:
set_snmp_v2(info, &sess);
break;
case 3:
set_snmp_v3(info, &sess);
break;
}
if (!(session = snmp_open(&sess))) {
snmp_perror("snmp_open");
continue;
}
if (snmp_send(session, pdu)) {
} else {
snmp_perror("snmp_send");
}
free(protocol_ip);
}
}
snmp_free_pdu(pdu);
free(peer_ip);
The code of set_snmp_v2:
void set_snmp_v2(snmp_info *info, struct snmp_session *sess){
sess->version = SNMP_VERSION_2c;
sess->community = strdup(info->community);
sess->community_len = strlen(sess->community);
}
I have this error for the version 3 too (similar to the one above). For the version 1 there is no problem but the version 2c and 3 seems to trigger the errors. Can someone enlighten me about this error ?
Note: the purpose of the code is to scan a given network and detect all the snmp agent given iformations. The first code is just the copy of the inside of the async_request function.
EDIT: I forgot to put my include in the post.
#include <stdlib.h>
#include <stdio.h>
#include <regex.h>
#include <math.h>
#include <net-snmp/net-snmp-config.h>
#include <net-snmp/net-snmp-includes.h>
I resolved it! The problem was that each time I attempt to open a session I have to create a new pdu :
/* Openning the session */
if (!(session = snmp_open(&sess))) {
snmp_perror("snmp_open");
continue;
}
/* PDU creation */
pdu = snmp_pdu_create(SNMP_MSG_GETNEXT);
snmp_add_null_var(pdu, anOID, anOID_len);
/* Sending the request */
if (!snmp_send(session, pdu)) {
snmp_perror("snmp_send");
snmp_free_pdu(pdu);
}
But I'm puzzled because as it work I see that the request are not asynchronous and wait for a timeout to make the next request.