Search code examples
javasnmpnet-snmpsnmp4j

How to send my customized trap message to snmp manager?


In the below piece of code where to add my customized on-fly message

Description :

I have my manager running which is mentioned as NOCIP, Also have MIB file but on sending trap for specific OID the messages should vary though the trap is same for different scenarios

eg :

if ( ...) {

trap1 :customized message1

}

else if( ...) {

trap1 : customized message2

}

else{

trap2 : customized message3

}

public void sendSnmpV2Trap()
  {
    try
    {
      //Create Transport Mapping
      TransportMapping transport = new DefaultUdpTransportMapping();
      transport.listen();

      //Create Target
      CommunityTarget comtarget = new CommunityTarget();
      comtarget.setCommunity(new OctetString(community));
      comtarget.setVersion(SnmpConstants.version2c);
      comtarget.setAddress(new UdpAddress(ipAddress + "/" + port));
      comtarget.setRetries(2);
      comtarget.setTimeout(5000);

      //Create PDU for V2
      PDU pdu = new PDU();

      // need to specify the system up time
      pdu.add(new VariableBinding(SnmpConstants.sysUpTime, new OctetString(new Date().toString())));
      pdu.add(new VariableBinding(SnmpConstants.snmpTrapOID, new OID(trapOid)));
      pdu.add(new VariableBinding(SnmpConstants.snmpTrapAddress, new IpAddress(ipAddress)));


      pdu.setType(PDU.NOTIFICATION);

      //Send the PDU
      Snmp snmp = new Snmp(transport);
      System.out.println("Sending V2 Trap to " + ipAddress + " on Port " + port);
      snmp.send(pdu, comtarget);
      snmp.close();
    }
    catch (Exception e)
    {
      System.err.println("Error in Sending V2 Trap to " + ipAddress + " on Port " + port);
      System.err.println("Exception Message = " + e.getMessage());
    }
  }
}-

Solution

  • If you want your trap to contain a customized message, you should attach it as a VariableBinding.

    For example, if you want to pass an OctetString, you do

    pdu.add(new VariableBinding(<yourCustomOID>, new OctetString("This unit has caught fire")));
    

    Put that right after the code that adds the three already existing variables. Make sure the order of your varbinds matches what your MIB file advertises.

    I would try to break out the if-else logic into a separate method, and have it return the appropriate value for the OctetString (or whatever you're sending).