Generating TRAP in SNMP using SNMP4j

Author posted by Jitendra on Posted on under category Categories SNMP and tagged as Tags , with 18 Comments on Generating TRAP in SNMP using SNMP4j

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]

Related posts

18 thoughts on “Generating TRAP in SNMP using SNMP4j”

  1. 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. 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?

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

  4. 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.

  5. 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

  6. 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

  7. 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.

  8. 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.

  9. 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.

Leave a Reply

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