Reputation: 11
I have a project that involves using the SNMP protocol, and I'm using the NET-SNMP library. I have written C code for the client side (manager) of SNMP, and it works perfectly. However, on the server side, I need assistance with receiving SNMP incoming requests using C code and the NET-SNMP library. We are writing a C code for our project. Could you please help me?"
#include <net-snmp/net-snmp-config.h>
#include <net-snmp/net-snmp-includes.h>
int main(int argc, char **argv) {
netsnmp_session session, *ss;
netsnmp_pdu *pdu;
netsnmp_pdu *response;
oid anOID[MAX_OID_LEN];
size_t anOID_len;
int status;
int count = 0;
int running = 1;
// Initialize the SNMP library
init_snmp("snmpapp");
// Set up the SNMP session parameters
snmp_sess_init(&session);
session.peername = "192.168.100.76";
session.version = SNMP_VERSION_2c;
session.community = "public";
session.community_len = strlen(session.community);
// Open the SNMP session
ss = snmp_sess_open(&session);
if (!ss) {
snmp_perror("snmp_open");
exit(1);
}
// Loop to receive and process incoming requests
while (running) {
pdu = NULL;
if(!pdu)
{
continue;
}
// Block until a request is received
status = snmp_sess_read(ss, &pdu);
printf("pdu--->Command:%s",pdu->command);
//printf("status:%d\r\n",status);
if (status == STAT_SUCCESS && pdu) {
// Process the request based on its type
printf("OK\r\n");
switch (pdu->command) {
case SNMP_MSG_GET:
// Process a GET request
printf("Received GET request\n");
break;
case SNMP_MSG_GETNEXT:
// Process a GETNEXT request
printf("Received GETNEXT request\n");
break;
case SNMP_MSG_SET:
// Process a SET request
printf("Received SET request\n");
break;
case SNMP_MSG_TRAP:
// Process a TRAP request
printf("Received TRAP request\n");
break;
default:
// Unknown command
printf("Unknown request type\n");
break;
}
// Send a response to the request
if (pdu->command == SNMP_MSG_GET || pdu->command == SNMP_MSG_GETNEXT) {
response = snmp_pdu_create(SNMP_MSG_RESPONSE);
response->errstat = SNMP_ERR_NOERROR;
response->errindex = 0;
// Add a dummy variable to the response
anOID_len = MAX_OID_LEN;
if (snmp_parse_oid(".1.3.6.1.2.1.1.1.0", anOID, &anOID_len) == NULL) {
snmp_perror(".1.3.6.1.2.1.1.1.0");
} else {
snmp_add_var(response, anOID, anOID_len, 's', "Hello, world!");
}
status = snmp_synch_response(ss, pdu, response);
if (status != STAT_SUCCESS) {
snmp_perror("snmp_sess_send_response");
}
}
// Free the request PDU
snmp_free_pdu(pdu);
} else {
//printf("Failed to receive request\n");
}
}
// Clean up the SNMP session
snmp_close(ss);
// Shut down the SNMP library
snmp_shutdown("snmpapp");
return 0;
}
Upvotes: 1
Views: 391