SNMP4J

SNMP Walk Example using SNMP4J

This article is pretty straightforward. It’s an SNMP walk example using SNMP4J. SNMP is used in managing and monitoring network devices. It is an Internet standard protocol for managing devices on IP networks.

1. Tools and Prerequisites

  1. SNMP4J library
  2. Mars Eclipse

2. Create the Project

You may skip this process because this is a fairly simple example which can be made using a text editor. We’ll just do a quick Java project creation through Eclipse. Click on File -> New -> Java Project to create the project. Then create the com.javacodegeeks.example package. Next, create an empty SnmpWalk class. We’re not done yet. We have to add the SNMP4J library. Right-click on the project and go to Build Path -> Configure Build Path, then Libraries Tab -> Add External Jars… and add snmp4j-2.5.6.jar (latest version as of this writing).

3. Java Code and Code Walkthrough

The Java code below shows an SNMP walk on the ifTable of the interfaces a certain device. It starts out by creating the CommunityTarget object. This contains the community string, the target IP and port, the number of retries, the timeout value, and the SNMP version being used.
The doWalk method accepts the ifTable OID and the CommunityTarget object as parameters. A more detailed explanation of this method is described below. Lastly, the result is then printed to the console.

SnmpWalk.java

package com.javacodegeeks.example;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import org.snmp4j.CommunityTarget;
import org.snmp4j.Snmp;
import org.snmp4j.Target;
import org.snmp4j.TransportMapping;
import org.snmp4j.mp.SnmpConstants;
import org.snmp4j.smi.Address;
import org.snmp4j.smi.GenericAddress;
import org.snmp4j.smi.OID;
import org.snmp4j.smi.OctetString;
import org.snmp4j.smi.VariableBinding;
import org.snmp4j.transport.DefaultUdpTransportMapping;
import org.snmp4j.util.DefaultPDUFactory;
import org.snmp4j.util.TreeEvent;
import org.snmp4j.util.TreeUtils;

public class SnmpWalk {

	public static void main(String[] args) throws Exception {
		CommunityTarget target = new CommunityTarget();
		target.setCommunity(new OctetString("public"));
		target.setAddress(GenericAddress.parse("udp:x.x.x.x/161")); // supply your own IP and port
		target.setRetries(2);
		target.setTimeout(1500);
		target.setVersion(SnmpConstants.version2c);
		
		Map<String, String> result = doWalk(".1.3.6.1.2.1.2.2", target); // ifTable, mib-2 interfaces

		for (Map.Entry<String, String> entry : result.entrySet()) {
			if (entry.getKey().startsWith(".1.3.6.1.2.1.2.2.1.2.")) {
				System.out.println("ifDescr" + entry.getKey().replace(".1.3.6.1.2.1.2.2.1.2", "") + ": " + entry.getValue());
			}
			if (entry.getKey().startsWith(".1.3.6.1.2.1.2.2.1.3.")) {
				System.out.println("ifType" + entry.getKey().replace(".1.3.6.1.2.1.2.2.1.3", "") + ": " + entry.getValue());
			}
		}
	}

	public static Map<String, String> doWalk(String tableOid, Target target) throws IOException {
		Map<String, String> result = new TreeMap<>();
		TransportMapping<? extends Address> transport = new DefaultUdpTransportMapping();
		Snmp snmp = new Snmp(transport);
		transport.listen();

		TreeUtils treeUtils = new TreeUtils(snmp, new DefaultPDUFactory());
		List events = treeUtils.getSubtree(target, new OID(tableOid));
		if (events == null || events.size() == 0) {
			System.out.println("Error: Unable to read table...");
			return result;
		}

		for (TreeEvent event : events) {
			if (event == null) {
				continue;
			}
			if (event.isError()) {
				System.out.println("Error: table OID [" + tableOid + "] " + event.getErrorMessage());
				continue;
			}

			VariableBinding[] varBindings = event.getVariableBindings();
			if (varBindings == null || varBindings.length == 0) {
				continue;
			}
			for (VariableBinding varBinding : varBindings) {
				if (varBinding == null) {
					continue;
				}
				
				result.put("." + varBinding.getOid().toString(), varBinding.getVariable().toString());
			}

		}
		snmp.close();

		return result;
	}

}


You’ll need to provide your own SNMP agent IP address and port (highlighted). We are using SNMP version 2c. This example will walk the mib2.interfaces.ifTable. It will stop the walk when it is finished walking the ifTable tree (the VariableBinding OID does not have the same prefix). Once the walk is finished, the interface description and type are then printed out.

The TreeUtils (highlighted) API does the heavy lifting for us. TreeUtils retrieves a subtree of management values using SNMP GetNext Requests. GetNext is a request to discover available variables and their values. This process have been abstracted by this API. We are so lucky.

The results are then returned as a Map with the OID as the key and the values as type String.

4. Output

Your output should look something like the one below. You can verify it using a MIB browser.

Console Output

ifDescr.1: igb0
ifDescr.10: lo0
ifDescr.11: ovpns1
ifDescr.12: ovpnc2
ifDescr.2: igb1
ifDescr.3: igb2
ifDescr.4: igb3
ifDescr.5: igb4
ifDescr.6: igb5
ifDescr.7: pflog0
ifDescr.8: pfsync0
ifDescr.9: enc0
ifType.1: 6
ifType.10: 24
ifType.11: 23
ifType.12: 23
ifType.2: 6
ifType.3: 6
ifType.4: 6
ifType.5: 6
ifType.6: 6
ifType.7: 246
ifType.8: 247
ifType.9: 244

5. Summary of the SNMP Walk Example using SNMP4J

In this example, we learned to perform an SNMP walk using SNMP4J’s TreeUtils API. TreeUtils retrieved the subtree of management values for us. The multiple SNMP GetNext Requests have been abstracted by the API. Our programming has been made easier. A more optimized way of walking a MIB tree is to use the SNMP GetBulk Request introduced in SNMP version 2. With the GetBulk Request, the manger sends a single request for multiple iterations of the GetNext Request which is performed in the agent’s side. Whereas the SNMP walk performs multiple requests to the agent thus adding load on the network traffic.

6. Download the Source Code

This is an example of an SNMP Walk using SNMP4J.

Download
You can download the source code of this example here: snmp-walk-example-snmp4j.zip.

Joel Patrick Llosa

I graduated from Silliman University in Dumaguete City with a degree in Bachelor of Science in Business Computer Application. I have contributed to many Java related projects at Neural Technologies Ltd., University of Southampton (iSolutions), Predictive Technologies, LLC., Confluence Service, North Concepts, Inc., NEC Telecom Software Philippines, Inc., and NEC Technologies Philippines, Inc. You can also find me in Upwork freelancing as a Java Developer.
Subscribe
Notify of
guest

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

14 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Aqsa Ayub
Aqsa Ayub
6 years ago

why this program doesn’t retrieve port description of switch ?is there any other way of retrieving that?

The moon
The moon
5 years ago

Assumedly I have a method such as GetSubTree(Ipaddress, CommunityString, oid), I want to call it in Sql Server, how to do it? Please help me..thanks advance.

Rohit kumar
Rohit kumar
5 years ago

sir i need java snmp program getbulk agent program.

Rohit kumar
Rohit kumar
5 years ago

//Hello Sir this is my Snmp GetBulk Version 3 code.there is problem.when i was sending the request for server to agent.my agent can not be respond the server request.please sir help me where i am mistake in this code.here agent and server both code send. Java Snmp GetBulk Agent version 3 program. public class JavaExample implements CommandResponder { public static final OID sysDescr = new OID(“1.3.6.1.2.1.1.1.0”); private Snmp snmp; String SHADESAuthPassword; OctetString contextEngineID; OctetString contextName; public JavaExample() throws IOException { MessageDispatcher dispatcher = new MessageDispatcherImpl(); dispatcher.addMessageProcessingModel(new MPv3()); snmp = new Snmp(dispatcher, new DefaultUdpTransportMapping(new UdpAddress(“127.0.0.1/162”), true)); snmp.addCommandResponder(this); OctetString localEngineId = new… Read more »

Rohit
Rohit
5 years ago

yes sir port 162.its server send the request for agent.agent accept the request but it can not response.

Rohit
Rohit
5 years ago

ok sir. please give some help regarding snmp GETBULK agent version 3.

Paraddi
Paraddi
4 years ago

Getting the following compilation error for the above code.

Exception in thread “main” java.lang.Error: Unresolved compilation problem: 
Type mismatch: cannot convert from element type Object to TreeEvent

at SNMP_Walker/com.javacodegeeks.example.SnmpWalk.doWalk(SnmpWalk.java:58)
at SNMP_Walker/com.javacodegeeks.example.SnmpWalk.main(SnmpWalk.java:33)

Steven H
Steven H
4 years ago

You said that we needed to provide an snmp agent and port. Could you possibly show us how to create our own simulated agent on our local machine?

Back to top button