Generating TRAP in SNMP using SNMP4j

As we have discussed, Traps are like events. This is a way the SNMP agent pushes the information to client. Asynchronously, events can be fired to client from server (agent).

Example:

SNMP Trap Receiver:

package com.G2.SNMP.Trap.receiver;

import java.io.IOException;

import org.snmp4j.CommandResponder;
import org.snmp4j.CommandResponderEvent;
import org.snmp4j.CommunityTarget;
import org.snmp4j.MessageDispatcher;
import org.snmp4j.MessageDispatcherImpl;
import org.snmp4j.MessageException;
import org.snmp4j.PDU;
import org.snmp4j.Snmp;
import org.snmp4j.mp.MPv1;
import org.snmp4j.mp.MPv2c;
import org.snmp4j.mp.StateReference;
import org.snmp4j.mp.StatusInformation;
import org.snmp4j.security.Priv3DES;
import org.snmp4j.security.SecurityProtocols;
import org.snmp4j.smi.OctetString;
import org.snmp4j.smi.TcpAddress;
import org.snmp4j.smi.TransportIpAddress;
import org.snmp4j.smi.UdpAddress;
import org.snmp4j.transport.AbstractTransportMapping;
import org.snmp4j.transport.DefaultTcpTransportMapping;
import org.snmp4j.transport.DefaultUdpTransportMapping;
import org.snmp4j.util.MultiThreadedMessageDispatcher;
import org.snmp4j.util.ThreadPool;

public class TrapReceiver implements CommandResponder {
	public static void main(String[] args) {
		TrapReceiver snmp4jTrapReceiver = new TrapReceiver();
		try {
			snmp4jTrapReceiver.listen(new UdpAddress("localhost/162"));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * Trap Listner
	 */
	public synchronized void listen(TransportIpAddress address)
			throws IOException {
		AbstractTransportMapping transport;
		if (address instanceof TcpAddress) {
			transport = new DefaultTcpTransportMapping((TcpAddress) address);
		} else {
			transport = new DefaultUdpTransportMapping((UdpAddress) address);
		}

		ThreadPool threadPool = ThreadPool.create("DispatcherPool", 10);
		MessageDispatcher mDispathcher = new MultiThreadedMessageDispatcher(
				threadPool, new MessageDispatcherImpl());

		// add message processing models
		mDispathcher.addMessageProcessingModel(new MPv1());
		mDispathcher.addMessageProcessingModel(new MPv2c());

		// add all security protocols
		SecurityProtocols.getInstance().addDefaultProtocols();
		SecurityProtocols.getInstance().addPrivacyProtocol(new Priv3DES());

		// Create Target
		CommunityTarget target = new CommunityTarget();
		target.setCommunity(new OctetString("public"));

		Snmp snmp = new Snmp(mDispathcher, transport);
		snmp.addCommandResponder(this);

		transport.listen();
		System.out.println("Listening on " + address);

		try {
			this.wait();
		} catch (InterruptedException ex) {
			Thread.currentThread().interrupt();
		}
	}

	/**
	 * This method will be called whenever a pdu is received on the given port
	 * specified in the listen() method
	 */
	public synchronized void processPdu(CommandResponderEvent cmdRespEvent) {
		System.out.println("Received PDU...");
		PDU pdu = cmdRespEvent.getPDU();
		if (pdu != null) {
			System.out.println("Trap Type = " + pdu.getType());
			System.out.println("Variables = " + pdu.getVariableBindings());
			}
		}
	}

Version 1 Trap Sender:

package com.G2.SNMP.Trap.Sender;

import org.snmp4j.CommunityTarget;
import org.snmp4j.PDU;
import org.snmp4j.PDUv1;
import org.snmp4j.Snmp;
import org.snmp4j.TransportMapping;
import org.snmp4j.mp.SnmpConstants;
import org.snmp4j.smi.IpAddress;
import org.snmp4j.smi.OID;
import org.snmp4j.smi.OctetString;
import org.snmp4j.smi.UdpAddress;
import org.snmp4j.transport.DefaultUdpTransportMapping;

public class TrapSenderVersion1 {

	public static final String community = "public";

	// Sending Trap for sysLocation of RFC1213
	public static final String Oid = ".1.3.6.1.2.1.1.8";

	//IP of Local Host
	public static final String ipAddress = "127.0.0.1";

	//Ideally Port 162 should be used to send receive Trap, any other available Port can be used
	public static final int port = 162;

	public static void main(String[] args) {
		TrapSenderVersion1 trapV1 = new TrapSenderVersion1();
		trapV1.sendTrap_Version1();
	}
	/**
	 * This methods sends the V1 trap to the Localhost in port 162
	 */
	public void sendTrap_Version1() {
		try {
			// Create Transport Mapping
			TransportMapping transport = new DefaultUdpTransportMapping();
			transport.listen();

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

			PDUv1 pdu = new PDUv1();
			pdu.setType(PDU.V1TRAP);
			pdu.setEnterprise(new OID(Oid));
			pdu.setGenericTrap(PDUv1.ENTERPRISE_SPECIFIC);
			pdu.setSpecificTrap(1);
			pdu.setAgentAddress(new IpAddress(ipAddress));

			// Send the PDU
			Snmp snmp = new Snmp(transport);
			System.out.println("Sending V1 Trap... Check Wheather NMS is Listening or not? ");
			snmp.send(pdu, cTarget);
			snmp.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}

Output:

Listening on 127.0.0.1/162
Received PDU…
Trap Type = -92
Variables = []

Version 2 Trap Sender:

package com.G2.SNMP.Trap.Sender;

import java.util.Date;

import org.snmp4j.CommunityTarget;
import org.snmp4j.PDU;
import org.snmp4j.Snmp;
import org.snmp4j.TransportMapping;
import org.snmp4j.mp.SnmpConstants;
import org.snmp4j.smi.IpAddress;
import org.snmp4j.smi.OID;
import org.snmp4j.smi.OctetString;
import org.snmp4j.smi.UdpAddress;
import org.snmp4j.smi.VariableBinding;
import org.snmp4j.transport.DefaultUdpTransportMapping;

public class TrapSenderVersion2 {

	public static final String community = "public";

	// Sending Trap for sysLocation of RFC1213
	public static final String Oid = ".1.3.6.1.2.1.1.8";

	//IP of Local Host
	public static final String ipAddress = "127.0.0.1";

	//Ideally Port 162 should be used to send receive Trap, any other available Port can be used
	public static final int port = 162;

	public static void main(String[] args) {
		TrapSenderVersion2 trapV2 = new TrapSenderVersion2();
		trapV2.sendTrap_Version2();
	}
	/**
	 * This methods sends the V1 trap to the Localhost in port 162
	 */
	public void sendTrap_Version2() {
		try {
			// Create Transport Mapping
			TransportMapping transport = new DefaultUdpTransportMapping();
			transport.listen();

			// Create Target
			CommunityTarget cTarget = new CommunityTarget();
			cTarget.setCommunity(new OctetString(community));
			cTarget.setVersion(SnmpConstants.version2c);
			cTarget.setAddress(new UdpAddress(ipAddress + "/" + port));
			cTarget.setRetries(2);
			cTarget.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(
					Oid)));
			pdu.add(new VariableBinding(SnmpConstants.snmpTrapAddress,
					new IpAddress(ipAddress)));

			pdu.add(new VariableBinding(new OID(Oid), new OctetString(
					"Major")));
			pdu.setType(PDU.NOTIFICATION);

			// Send the PDU
			Snmp snmp = new Snmp(transport);
			System.out.println("Sending V2 Trap... Check Wheather NMS is Listening or not? ");
			snmp.send(pdu, cTarget);
			snmp.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}

Output:

Listening on 127.0.0.1/162
Received PDU…
Trap Type = -89
Variables = [1.3.6.1.2.1.1.3.0 = Wed Feb 16 01:17:02 IST 2011, 1.3.6.1.6.3.1.1.4.1.0 = 1.3.6.1.2.1.1.6, 1.3.6.1.6.3.18.1.3.0 = 127.0.0.1, 1.3.6.1.2.1.1.6 = Major]


Posted

in

by

Tags:

Comments

22 responses to “Generating TRAP in SNMP using SNMP4j”

  1. karthik Avatar
    karthik

    hi shiva,
    After implementing the above code,
    When I use simulator to receive trap messages, I am getting the below error
    “Incorrect version or decode error”

    Please help me to resolve

    Thanx in advance
    Regards,
    Karthik

  2. Jitendra Zaa Avatar

    Hi Karthik,
    Few people also had same problem but that it is because of there environment. Please check this thread
    http://www.ms-news.net/f2630/snmp-based-on-all-traps-alert-doesnt-work-4319309.html

  3. Andrey Avatar
    Andrey

    Hi! Using your example (thanks for it! 🙂 for snmp v1 – trap sending is okay (I implemented it with DefaultTcpTransportMapping). The question is – is there a method to examine if trap message was really recieved by recipient? For example, your code works without any exceptions even for unexisting ip address (not bad formatted, but unexisting). I know that Tcp protokol itself supports delievery control, but why no errors while sendin?

    1. Jitendra Zaa Avatar

      Thanks Andrey,
      I haven’t worked on this type of requirement. I will surely update you on this.

      Regards,
      Jitendra Zaa

  4. rajshekar Avatar

    hey can you give me the for version 3 trap.urgent. and by the way thanks for the version 1 & 2 . they work fine.

  5. Regar Avatar
    Regar

    Could you give a trick to display received trap on a web ( i’m confuse because web using http protocol)
    Thank you.

  6. Regar Avatar
    Regar

    i’m sorry for asking again.

    how can I get trap complete data, like Generic trap type, Enterprise, Time stamp, Specific trap code, Agent address. Thank you.

  7. youcef Avatar
    youcef

    im getting this message when trying to start the receiver “Address already in use: Cannot bind” and im not starting any instance of the receiver , i tried to restar eclipse and the computer but nothing works

    1. Ram Avatar
      Ram

      Try to run as root user in linux

  8. Ahmed Ayedi Avatar
    Ahmed Ayedi

    thanks a lot

  9. Umar Farooq Avatar
    Umar Farooq

    i an new here kindly help me.. i want to receive information but my program stops on message that Listening on ip address but i don’t know how it can get information i am running just trap receiver class

  10. Rama Krishnan Avatar
    Rama Krishnan

    SNMP V3 trap sender example please ????????

  11. haifzhan Avatar
    haifzhan

    Really good demo, thanks!

  12. Pathmasri Ambegoda Avatar
    Pathmasri Ambegoda

    Can any body tell me if there is a way to send a custome text message in an SNMP trap?

  13. Ram Avatar
    Ram

    How to send SNMP v3 traps ??????????????

  14. Shailesh Avatar
    Shailesh

    If you change the community string in sender for SNMPv2 then also it is accepting.
    I believe it should not accept because this community string is used for authentication.

  15. Shailesh Avatar
    Shailesh

    If I change the community String in sender V2 only then also it is accepting. I believe it should not because community string is used for authentication.

  16. Praveen Avatar
    Praveen

    How to send the SNMP v2 traps to mutiple HOSTS?
    I am using iReasoning MIB browser. I configured mib browser on my other laptop congirured the respective ip’s
    i am unable to receive the trap to other receiver!
    Please help me.

  17. srijini Avatar
    srijini

    hi, thanks for your post. i used it and worked fine for me(version 1).
    But my requirement there need to send custom message .

    I used
    transport.sendMessage(cTarget.getAddress(), “{\”msg\”:\”hiiii\”}”.getBytes());
    above code before snd trap.
    but got error “Incorrect version or decoder”

  18. srijini Avatar
    srijini

    Nice post.
    i need to send long text morethan size 10k using this code.
    i used :
    pdu.add(new VariableBinding(new OID(new int[] { 1, 3, 6, 1, 2, 1, 1, 1 }), new OctetString(“LONG DATA”)));
    but there showing error : “Read error occured (10040) “.
    Can u pls give me a reply.
    Thank in advance

  19. Jonathan Hopper Avatar
    Jonathan Hopper

    Thanks for this sample. I just want to add: I had issues with

    Version 1 Trap Sender:

    I didnt understand from this sample that ‘setEnterprise’ OID was the OID of the enterprise, not the trap you wish to send. and then ‘setSpecificTrap’ is the last bit of the OID of the trap to send.

    These two bits get put togeather for the trap OID: enterpriseoid.0.specificTrapValue

    Took me ages, so sharing the knowledge.

  20. Prem Avatar

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.