15 December 2008 ~

Multi Threaded Trap Receiver using SNMP4J


The entry briefly touched upon creating a multithreaded Trap receiver using SNMP4J. This is based on example shipped with SNMP4J

Pre-requisite

  •  SNMP4J
  •  Log4j

Structure

For complete source have a look at the class org.snmp4j.test. MultiThreadedTrapReceiver.java shipped with SNMP4J distribution

Logical structure of the program

  • Create Socket for accepting Traps
  • Create a Thread pool to process PDU’s
  • Process the Traps

Let’s get into the code

Lets address the Listener creation steps

private void init() throws UnknownHostException, IOException {
 
    threadPool = ThreadPool.create("Trap", 2);
 
    dispatcher = MultiThreadedMessageDispatcher(threadPool,
                                           new MessageDispatcherImpl());
 
    listenAddress = GenericAddress.parse(System.getProperty("snmp4j.listenAddress",
                                                "udp:0.0.0.0/162"));
 
    TransportMapping transport;
 
    if (listenAddress instanceof UdpAddress) {
      transport = new DefaultUdpTransportMapping((UdpAddress)listenAddress);
    } else {
      transport = new DefaultTcpTransportMapping((TcpAddress)listenAddress);
    }
 
    snmp = new Snmp(dispatcher, transport);
    snmp.getMessageDispatcher().addMessageProcessingModel(new MPv1());
    snmp.getMessageDispatcher().addMessageProcessingModel(new MPv2c());
    snmp.getMessageDispatcher().addMessageProcessingModel(new MPv3());
 
    USM usm = new USM(SecurityProtocols.getInstance(),
                      new OctetString(MPv3.createLocalEngineID()), 0);
    SecurityModels.getInstance().addSecurityModel(usm);
    snmp.listen();
  }

Here we see that we have created Transport mapping to Listener on port 162. Next we add all three Message processing models, so that we can process Traps received from all three versions of SNMP (V1, V2C and V3). For SNMPv3, we add a Security model.

That’s it done. We listen and process the traps.

The default implementation of processPdu() in this class, just dumps some statistics on the output.

Customization’s

Let’s see what all can we do with this default example

  • Set only the SNMP version you want to support
  • Customize the Security Model for SNMP V3
  • The whole logic lies on processPDU(). You can take complete control of how to process the message and subsequent processing of the message like dumping it to database etc.

Sphere: Related Content

Leave a Reply