Create SNMP Client in JAVA Using SNMP4j

Get articles everyday as a email directly to your inbox:
Click to publicize, if you like this article :

There are lots of open source library for SNMP is available, even java have library for the same,  But in this article I will explain a simple example of using SNMP4j in JAVA to create a simple client which will display the hardware information.

Note : To run this program, SNMP service must be installed. Check this article to know that how to install SNMP in Windows XP.

Download libraries from http://www.snmp4j.org/html/download.html

Create Simple NMS (Network management station / Client) in JAVA using SNMP4j:


package com.G2.SNMP.client;

import java.io.IOException;

import org.snmp4j.CommunityTarget;
import org.snmp4j.PDU;
import org.snmp4j.Snmp;
import org.snmp4j.Target;
import org.snmp4j.TransportMapping;
import org.snmp4j.event.ResponseEvent;
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;

public class SNMPManager {

Snmp snmp = null;
String address = null;

/**
* Constructor
* @param add
*/
public SNMPManager(String add)
{
address = add;
}

public static void main(String[] args) throws IOException {
/**
* Port 161 is used for Read and Other operations
* Port 162 is used for the trap generation
*/
SNMPManager client = new SNMPManager("udp:127.0.0.1/161");
client.start();
/**
* OID - .1.3.6.1.2.1.1.1.0 => SysDec
* OID - .1.3.6.1.2.1.1.5.0 => SysName
* => MIB explorer will be usefull here, as discussed in previous article
*/
String sysDescr = client.getAsString(new OID(".1.3.6.1.2.1.1.1.0"));
System.out.println(sysDescr);
}

/**
* Start the Snmp session. If you forget the listen() method you will not
* get any answers because the communication is asynchronous
* and the listen() method listens for answers.
* @throws IOException
*/
private void start() throws IOException {
TransportMapping transport = new DefaultUdpTransportMapping();
snmp = new Snmp(transport);
// Do not forget this line!
transport.listen();
}

/**
* Method which takes a single OID and returns the response from the agent as a String.
* @param oid
* @return
* @throws IOException
*/
public String getAsString(OID oid) throws IOException {
ResponseEvent event = get(new OID[] { oid });
return event.getResponse().get(0).getVariable().toString();
}

/**
* This method is capable of handling multiple OIDs
* @param oids
* @return
* @throws IOException
*/
public ResponseEvent get(OID oids[]) throws IOException {
PDU pdu = new PDU();
for (OID oid : oids) {
pdu.add(new VariableBinding(oid));
}
pdu.setType(PDU.GET);
ResponseEvent event = snmp.send(pdu, getTarget(), null);
if(event != null) {
return event;
}
throw new RuntimeException("GET timed out");
}

/**
* This method returns a Target, which contains information about
* where the data should be fetched and how.
* @return
*/
private Target getTarget() {
Address targetAddress = GenericAddress.parse(address);
CommunityTarget target = new CommunityTarget();
target.setCommunity(new OctetString("public"));
target.setAddress(targetAddress);
target.setRetries(2);
target.setTimeout(1500);
target.setVersion(SnmpConstants.version2c);
return target;
}

}

Output:

Hardware: x86 Family 6 Model 23 Stepping 10 AT/AT COMPATIBLE – Software: Windows 2000 Version 5.1 (Build 2600 Multiprocessor Free)

Explanation of every method is documented in above program. In Next article, we will write a Java Program to create SNMP Agent.

You can leave a response, or trackback from your own site.
  • Guest1

    When i run this code it shows an error message of package org.snmp4j does not exist. Why is it?

    • http://www.facebook.com/jitendra.zaa Jitendra Zaa

      This is because you dont have required jar file in your environment.

      • Guest1

        Thanks a lot.

  • tuanhiep1232

    After sending Get/GetNext request to devices, I closed snmp connection using “snmp.close();”. But when i used TCPView tool to check connections, I found that snmp connection still exist. How to really close snmp connection.?
    Thanks and sorry for my English!

  • AMHiz

    how to install SNMP service on window 7 ?

    • AMhiz

      This time, There are NullPointerException. Why is it?

      • http://www.facebook.com/profile.php?id=100001738851391 ????????? ?????

        config windows snmp agent. This help’s :)
        Set Accepted community names in SNMP Service Properties [7 picture] – “public”.
        And add some IP [for example 127.0.0.1 if you test from your localhost] to “Accept SNMP packets from this hosts” [7 picture].
        http://www.loriotpro.com/ServiceAndSupport/How_to/InstallWXPAgent_EN.php
        have a nice day!

  • Ash852006

    I want to run this code on a remote client I changed 127.0.0.1 to xxx.xxx.xxx.xxx when I run the program it gives me :

    Exception in thread “main” java.lang.NullPointerException
        at SNMPManager.getAsString(SNMPManager.java:74)
        at SNMPManager.main(SNMPManager.java:46)

  • slash

    when i try to run this code its giving null pointer exception …I guess it may be due to timeout ..any help

  • Alejandro

    Thanks!!

    When I tried run this code, I had the same problem that had “aslary”, but when I change the IP address from 127.0.0.1 to a different one (a server IP address) it works.

    Thank you for the example.

  • http://twitter.com/macnet Jorge Monteiro

    thank you very much

  • Johan

    Hi there, your snmp4j blog series looks dangerously close to this, http://blog.jayway.com/2010/05/21/introduction-to-snmp4j, the code examples you are using is the same as that example and even the comments in the code is the same. However, there is no reference to the original article anywhere which I think would be in place.

  • http://www.facebook.com/magda.mihail Magda Stefan Mihail

    Hi. I have a question for you. If I would like to make a java program that will bind every 1 second a variable to a MIB oid that I’ve created (ex: form interfaces i’ve created ifATR and ifOWD) how can I do it. I would like this program just to bind the variable and every time i send a snmp request(using NETSNMP) to respond with that variable.

  • Daniel Estrázulas

    great !! This api is hard to learn, do you have any idea to how change this example for snmp v3 ?

     I’m trying to make a simple GET example using test agent but it always return the same OID ( maybe its a default mib at original test package example )

    What is more strange is that no matter which ones parameters for usm i choose on client… the agent always return the same OID with an incrementing value.

  • bizowiso

    Awesome post

  • Akira

    Thank you guys this code save me.

  • http://shivasoft.in Jitendra Zaa

    Hi RajShekhar,
    Currently i dont have the program for “snmpwalk”, if i will work or get time then definetly post here. If you will be able to resolve then please share with eceryone so that they can also get benefit.

    Regareds,
    Jitendra Zaa

  • rajshekar

    hey can i get similar program for snmpwalk. this program which you have given is for snmp get.

  • http://www.rajshekartargar.blogspot.com rajshekar

    hi aslary,

    i too had a similar error , i solved it like this:

    in the line:

    target.setCommunity(newOctetString(“public”));

    actually while setting community i had given the community name as demopublic. but here it was public. so i modified the line as follows:

    target.setCommunity(new OctetString(“demopublic”));

  • rajshekar

    Thanks for this article dude. before this had tried and tried unsuccessfully. final works. :)

  • RogerJames

    Thanks for the wonderful article. Could you please let us know the things that are required for running this program successfully…like setting params,installing variables,mibs etc.

  • cliff

    I am trying to iterate through a variable list of items but am not sure how to implement this, like a get next. I can iterate through my ManagedObjects that I have created with a specific OID but I want to query a group of items (slot numbers) where the base OID is the same and I want to have the query return baseOID.1, baseOID.2,…,baseOID.n

    How can I implement this in SNMP4j – any suggestions?
    Thanks

    • http://shivasoft.in Jitendra Zaa

      Hi Cliff,
      You can write your own logic. Create a string which have fixed OID and then every time concatenate number and use line no 45,46 and 47 in loop. Its totally depend on your environment. Please elaborate your need if it does not fulfill answer to your query.

      Thanks,
      Jitendra Zaa

  • aslary

    hi zaa,
    first thank you for quit response.
    I am using win7-> could this be a problem?

    best regards

  • http://shivasoft.in Jitendra Zaa

    the OID, which you are passing is correct ? Please take the help of MIB explorer which is explained in previous article.

    Thanks,
    Jitendra Zaa

  • http://shivasoft.in Jitendra Zaa

    Hi aslary,
    In eclipse, right click on project, select Build path option and then select import jars.

    Thanks

  • aslary

    hi,
    i know now how to get add an external jar file
    but i get an error ->

    Exception in thread “main” java.lang.NullPointerException
    at SNMPManager.getAsString(SNMPManager.java:69)
    at SNMPManager.main(SNMPManager.java:44)

    69: return event.getResponse().get(0).getVariable().toString();

    help:)

  • aslary

    hi,
    how can i can add the above snmp library to eclipse-IDE.
    I am newbie so please explain it step by step.

    • Suresh V

      @ aslary, select your current project, from the menu choose “Project” and opt for properties in the drop down menu. This opens a Project properties window, select the Libraries tab and click “Add external JARs” button.

  • Pingback: Creating SNMP Agent (Server) in JAVA using SNMP4j | Shiva Blog