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


  •  SNMP4J
  •  Log4j


For complete source have a look at the class org.snmp4j.test. 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",

    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);

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.


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.

10 thoughts on “Multi Threaded Trap Receiver using SNMP4J

  1. Yeah that’s great – multi-threaded. You should point out though that if you want to guarantee processing of the traps in the order they were received (for example, if you are monitoring transitions in state which is what Traps are all about…), this approach is not recommended. Why? Because, when processing the traps via a threadpool or similar concurrent fashion, you cannot guarantee they will be processed in the order they were received. Rather, we would only be assuming they will be processed in the order they are received due to the length of time between each trap being received being large enough under normal operation such that the probability of processing the second trap before the first becomes almost nill. However this is still only an assumption. When freak network behavior occurs, as is common during large outages when floods of traps are being generated, this assumption often leads to unpredictable results (and at a moment when the network needs the solution to be most accurate..).

    • Hi,

      Below is my complete code. I am able to receive the traps with security level “NOAUTH_NOPRIV” but I do not get any trap in case of “AUTH_NOPRIV” and “AUTH_PRIV” security level. Assist me in case something is missed..

      import java.util.Vector;

      import org.snmp4j.CommandResponder;
      import org.snmp4j.CommandResponderEvent;
      import org.snmp4j.MessageDispatcherImpl;
      import org.snmp4j.Snmp;
      import org.snmp4j.TransportMapping;
      import org.snmp4j.smi.Address;
      import org.snmp4j.smi.OctetString;
      import org.snmp4j.smi.UdpAddress;
      import org.snmp4j.smi.VariableBinding;
      import org.snmp4j.transport.DefaultUdpTransportMapping;
      import org.snmp4j.util.MultiThreadedMessageDispatcher;
      import org.snmp4j.util.ThreadPool;

      public class SnmpServer implements CommandResponder {
      private MultiThreadedMessageDispatcher dispatcher;

      private Snmp snmp = null;

      private Address listenAddress;

      private ThreadPool threadPool;

      private void init() throws UnknownHostException, IOException {
      threadPool = ThreadPool.create(“Trap”, 2);
      dispatcher = new MultiThreadedMessageDispatcher(threadPool, new MessageDispatcherImpl());
      listenAddress = new UdpAddress(“localhost/162”);
      TransportMapping transport;

      transport = new DefaultUdpTransportMapping((UdpAddress) listenAddress);

      snmp = new Snmp(dispatcher, transport);
      snmp.getMessageDispatcher().addMessageProcessingModel(new MPv1());
      snmp.getMessageDispatcher().addMessageProcessingModel(new MPv2c());
      snmp.getMessageDispatcher().addMessageProcessingModel(new MPv3());
      final USM usm = new USM(SecurityProtocols.getInstance(), new OctetString(MPv3.createLocalEngineID()), 0);
      final String userName = “anuj”;

      final String authenticationPwd = “temptemptemptemp”;
      final String privacyPwd = “temptemptemptemp”;
      final byte[] localEngineId = MPv3.createLocalEngineID();
      //Add user to the USM
      new OctetString(userName),
      new OctetString(localEngineId),
      new UsmUser(new OctetString(userName), AuthMD5.ID, new OctetString(authenticationPwd), PrivDES.ID,
      new OctetString(privacyPwd), new OctetString(localEngineId)));


      public void run() {
      try {
      } catch (final Exception ex) {

      public synchronized void processPdu(final CommandResponderEvent respEvnt) {
      if (respEvnt != null && respEvnt.getPDU() != null) {
      final Vector recVBs = respEvnt.getPDU().getVariableBindings();
      for (int i = 0; i < recVBs.size(); i++) {
      final VariableBinding recVB = recVBs.elementAt(i);
      System.out.println(recVB.getOid() + " : " + recVB.getVariable());


      public static void main(final String[] args) {
      final SnmpServer server = new SnmpServer();;



      • @Anuj – I am afraid I dont have a solution for you. This is with SNMPv3 and its been very very long since I worked with SNMP.

  2. Hi Ashish,
    I have requirement like i have alerts/errors info maintain my application but previous we are displayed in the Google maps related to one of my client(have form factor devices we are maintained that).but they wants those alerts or errors into Snmp traps how we can convert that errors info into snmp traps and how we can send the those info to them..
    what are requirements for developing these applications can u provide samples for that ..
    Iam new and fresher on this entire domain..

  3. Hi Ashish,

    My Application when configured to use windows trap stack registers with snmp trap service at startup.
    If my application starts before windows trap service , then my app has not registered to receive traps so no traps arrive.
    When SNMP started my application should automatically registered.
    how to solve this.

  4. hii ashish,
    this is my agent code.this is not respond to my server.please ask me where i mistake in this code.

    public void processPdu(CommandResponderEvent event)
    System.out.println(“Received PDU “+event);
    ScopedPDU pdu = (ScopedPDU) event.getPDU();
    switch (pdu.getType())
    case PDU.GETBULK:
    List responses = newArrayList(pdu.size());
    for (VariableBinding v : pdu.getVariableBindings())
    OID oid = v.getOid();
    // Answer the usual SNMP requests
    if (sysDescr.equals(oid))
    responses.add(new VariableBinding(oid, new OctetString(“My System description”)));
    UserTarget comm = new UserTarget();
    comm.setSecurityName(new OctetString(“SHADES”));

    ScopedPDU resp = new ScopedPDU();
    System.out.println(String.format(“Sending response PDU to %s/%s: %s”, event.getPeerAddress(), new String(event.getSecurityName()), resp));

    snmp.send(resp, comm);
    catch (IOException e)
    System.err.println(String.format(“Unable to send response PDU! (%s)”, e.getMessage()));
    System.err.println(String.format(“Unhandled PDU type %s.”, PDU.getTypeString(pdu.getType())));

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.