Implementing Trap Sender using SNMP4J

In this post, we shall implement a Trap Sender using SNMP4J. We may choose to use Apache MINA for sending Traps or can resort to using DatagramSocket class directly.

This shall be the logical flow of the implementation

  • Get the encoded Trap Data
  • Send the Trap 
Lets look at the first component, on getting the encoded Trap data


The code snippet above shows a simple way of creating and encoding a Trap PDU. Essentially, we create an instance of PDU class and sets the type as Trap. This is important, else SNMP4J shall throw an exception. Thereafter, we can set the trap parameters. Here, we have hardcoded the parameters, there can be custom implementations that can take these from config files or from UI. After setting the parameters, we just call the encode function passing the Output stream and collect the byte array to be sent.

Sending part is even simpler     

The send code is preety straight forward. Here we have used Datagram Socket, we can use Apache MINA UDP Client implementation to send the trap as well.


One thought on “Implementing Trap Sender using SNMP4J

  1. Ashish,

    Thanks for this article, really usefull for a person like me who had downloaded snmp4j yesterday for writing a trap sender. However as you may have guessed, I am struggling with sending a v2c trap. Can you provide more info for the same please.

    Appreciate your help.


Leave a Reply to Amit Cancel 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.