Create SNMP Client in JAVA Using SNMP4j

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.


Posted

in

by

Tags:

Comments

76 responses to “Create SNMP Client in JAVA Using SNMP4j”

  1. […] Creating SNMP Agent (Server) in JAVA using SNMP4j Posted by admin on February 24th, 2011 In Previous article, we have seen that how to create SNMP client in JAVA using SNMP4j. […]

  2. aslary Avatar
    aslary

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

    1. Suresh V Avatar
      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.

      1. Hari Avatar
        Hari

        hi,

        Above code i have to run in my machine (ubuntuOS).following exception is comming any one help me plz iam new from this.

        java.net.BindException: Permission denied
        at java.net.PlainDatagramSocketImpl.bind0(Native Method)
        at java.net.AbstractPlainDatagramSocketImpl.bind(AbstractPlainDatagramSocketImpl.java:85)
        at java.net.DatagramSocket.bind(DatagramSocket.java:373)
        at java.net.DatagramSocket.(DatagramSocket.java:229)
        at java.net.DatagramSocket.(DatagramSocket.java:282)
        at org.snmp4j.transport.DefaultUdpTransportMapping.(DefaultUdpTransportMapping.java:100)
        at com.aurus.SnmpClient.start(SnmpClient.java:40)
        at com.aurus.SnmpClient.(SnmpClient.java:30)
        at com.aurus.SnmpClient.main(SnmpClient.java:60)

        1. Hari Avatar
          Hari

          sorry ,above is another example code below code is this code pls help me any one..

          Exception in thread “main” org.snmp4j.MessageException: Operation not permitted
          at org.snmp4j.MessageDispatcherImpl.sendPdu(MessageDispatcherImpl.java:526)
          at org.snmp4j.Snmp.sendMessage(Snmp.java:1004)
          at org.snmp4j.Snmp.send(Snmp.java:898)
          at org.snmp4j.Snmp.send(Snmp.java:878)
          at SNMPManager.get(SNMPManager.java:84)
          at SNMPManager.getAsString(SNMPManager.java:68)
          at SNMPManager.main(SNMPManager.java:44)
          Caused by: java.io.IOException: Operation not permitted
          at java.net.PlainDatagramSocketImpl.send(Native Method)
          at java.net.DatagramSocket.send(DatagramSocket.java:629)
          at org.snmp4j.transport.DefaultUdpTransportMapping.sendMessage(DefaultUdpTransportMapping.java:117)
          at org.snmp4j.transport.DefaultUdpTransportMapping.sendMessage(DefaultUdpTransportMapping.java:42)
          at org.snmp4j.MessageDispatcherImpl.sendMessage(MessageDispatcherImpl.java:202)
          at org.snmp4j.MessageDispatcherImpl.sendPdu(MessageDispatcherImpl.java:503)
          … 6 more

  3. aslary Avatar
    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:)

    1. ninjacha0s Avatar
      ninjacha0s

      Same issue, how to get this resolved?

    2. sravani Avatar
      sravani

      does the problem resolved?

        1. Eric Parayre Avatar
          Eric Parayre

          Hi Anil, the problem is that I don’t have the package “package com.G2.SNMP.client”.
          So this code can’t compile. Where can I get this package ?
          Thanks for the answer.

  4. Jitendra Zaa Avatar

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

    Thanks

    1. kavyakabilan Avatar
      kavyakabilan

      Hi,this is kavya i have the snmp4j jars imported already still i get the error.

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

  5. Jitendra Zaa Avatar

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

    Thanks,
    Jitendra Zaa

  6. aslary Avatar
    aslary

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

    best regards

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

    1. Jitendra Zaa Avatar

      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

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

  9. rajshekar Avatar
    rajshekar

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

  10. rajshekar Avatar

    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”));

  11. rajshekar Avatar
    rajshekar

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

  12. Jitendra Zaa Avatar

    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

  13. Akira Avatar
    Akira

    Thank you guys this code save me.

  14. bizowiso Avatar
    bizowiso

    Awesome post

  15. Daniel Estrázulas Avatar
    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.

  16. Magda Stefan Mihail Avatar

    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.

  17. Johan Avatar
    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.

  18. Jorge Monteiro Avatar

    thank you very much

  19. Alejandro Avatar
    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.

  20. slash Avatar
    slash

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

  21. Ash852006 Avatar
    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)

    1. moonw Avatar
      moonw

      Hi folks, I had the same issue, and I have solved it checking that smtp service is enabled (seems that the error message cause is related with an exception that is not evaluated when the service is not enabled). Then just check that your service is enabled and well configured.

      1. ff kk Avatar
        ff kk

        how should it be configured?

        1. ninajcha0s Avatar
          ninajcha0s

          Did you ever figure out ?

  22. AMHiz Avatar
    AMHiz

    how to install SNMP service on window 7 ?

    1. AMhiz Avatar
      AMhiz

      This time, There are NullPointerException. Why is it?

      1. ????????? ????? Avatar

        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!

  23. tuanhiep1232 Avatar
    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!

  24. Guest1 Avatar
    Guest1

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

    1. Jitendra Zaa Avatar

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

      1. Guest1 Avatar
        Guest1

        Thanks a lot.

  25. Ahmed Ayedi Avatar
    Ahmed Ayedi

    When i run this code it shows an error message:

    Exception in thread “main” java.lang.NullPointerException

    at SNMPManager.getAsString(SNMPManager.java:71)

    at SNMPManager.main(SNMPManager.java:46)

    can you help me please

    1. Overlight Avatar
      Overlight

      I also have the same error

  26. sog Avatar
    sog

    hello, I hope you can give me your opinion….
    This example could be used for a Network Monitoring System, i hope your answer, and thank you very much…

  27. Mew Avatar
    Mew

    Thanks for the code.
    I wondering if I want to get the ip address that all connected to the router. Can I do that?

  28. Nupur Bora Avatar
    Nupur Bora

    Hello, i m working on a project of NMS using SNMP protocol. I will develop a android(java based) application, by which i will manage networks devices like routers,switches etc. So can you help me to this coding part of java. I will very thankful to you.

  29. Yuvraj Avatar
    Yuvraj

    HI Jitendra,
    Could you plz guide how we can load/read/compile our own mibs. i mean how to proceed with our own mibs

  30. palavesamuthu Avatar
    palavesamuthu

    HI Jitendra,

    The above program work well, thanks for this.
    Now I want to list all the devices details which are connected in my network, How can I do this??

  31. karthik Avatar
    karthik

    Hello Jitendra,
    Thanks for the example and it has been very helpful in understanding the snmp4j framework. But i wanted to ask you if this would work for an ipv6 address? if so,then what is the format for the ipv6 address scheme.?
    i tried “udp:[xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx]/161” but that doesn’t seem to be working. Can you shed some light on this?. Thanks in advance.

  32. Surendra Kumar Avatar
    Surendra Kumar

    how to copy and pate this code without line number .

  33. Simla Avatar
    Simla

    Hi Jitendra,
    I am currently working on SNMP monitoring and for now i’m working with localhost

    I’m trying to get CPU and memory usage with SNMP. I have a Java code which takes the oid and runs the “get” command. I can reach the values with MIB-II. However when i import HOST-RESOURCES-MIB in the code i can’t get CPU information it returns Null. But some oids work properly in HOST-RESOURCES-MIB.

    For example:

    hrSystemUpTime(.1.3.6.1.2.1.25.1.1.0) gives me the value 3:51:15.07
    hrProcessorLoad(.1.3.6.1.2.1.25.3.3.1.2.0) gives me the value Null

    What is the problem?

  34. Curtis Newton Avatar
    Curtis Newton

    errors : client start is privare and snmpmanager not defined
    nice….

    1. Muhammad Osama Avatar
      Muhammad Osama

      You need to change “SNMPManager” as your class name.
      For e.g
      Public class abc{}
      abc client = new abc(” “);

  35. Juan Carlos Jirón Avatar
    Juan Carlos Jirón

    EXCELENT my friend! thank you so much for your time writing this entry.
    I’m coding this in a spring server

  36. asd Avatar
    asd

    I am getting null in pdu..Can you help?

    1. aqsa ayub Avatar

      facing the same problem ,did you get the solution?

  37. Krishna Aryal Avatar
    Krishna Aryal

    I want to know about getbulk from given OIDs?

  38. Evoup Yin Avatar

    Successfully ran in linuxmint17,thanks

  39. Massinissa Bendaikha Avatar
    Massinissa Bendaikha

    Windows 10
    Eclipse Helios Service Release 1
    SNMP4J 2.5.11

    Worked like a charm since first run. All I did was changing the ip to my ethernet connected DSE 892 gateway.

    SNMPManager client = new SNMPManager(“udp:127.0.0.1/161”);
    ==>
    SNMPManager client = new SNMPManager(“udp:192.168.1.100/161”);

    Thanks for this great piece of code. Way better than a hundred tutorials.

    1. aqsa ayub Avatar

      mine is not working 🙁 although i did the same change…please help if you can

  40. Kramti Avatar
    Kramti

    Hello
    can you help me please
    My project is about Design of an SNMP interface for remote UPS supervision with java

  41. aqsa ayub Avatar

    It’s working now…can someone guide me here that how can I get a list of active interfaces from a cisco switch using this program, Is there any oid for retrieving this data from switch..Please help if someone can.. 🙂

  42. sugadev Avatar
    sugadev

    im received the error message::
    Exception in thread “main” java.lang.NullPointerException

    1. Ray Avatar
      Ray

      Did you happen to fix you issues with this? I am having the same issue.

      1. Pedro Avatar
        Pedro

        the device must be active SNMP. In another case you get NullPointerException

  43. Pedro Avatar
    Pedro

    I did a loop for with 38 to 46 lineswith the idea to scan an ip range. If the UDP got a snmp device work well but if the ip is empty or without snmp device the program down with the Exception java.lang.NullPointerException. How I can capture the exception correctly and to continue the program?

  44. Armando Gonzalez Avatar
    Armando Gonzalez

    activate the service in windows… solution for SNMPManager.getAsString (SNMPManager.java:74) NullPointer…

    https://www.youtube.com/watch?v=mE793eEpffo

  45. Aparna Choudhary Avatar
    Aparna Choudhary

    hi , I am facing problem to fetch the table item from snmp table(iftable ) OID (.1.3.6.1.2.1.2.2) of RFC1213.mib from TableUtils.getTable snmp4j API jar.is can you please help me regarding that and suggest how to retrieve data from snmp table??

  46. Aparna Avatar
    Aparna

    Hi , I am trying to fetch table oid data from snmp4j (TableUtils.getTable ) api but not able to get rows /Table events from it.Can you please help me???

  47. Rohit Kumar Avatar
    Rohit Kumar

    Hello sir this java Snmp version3 getbulk agent and server example.sir problem is server send the request for agent and agent accept the request.but agent can’t respond the server.please help…

  48. […] as an example a following code from https://www.jitendrazaa.com/blog/java/snmp/create-snmp-client-in-java-using-snmp4j/ to monitor a network when I send OIDs to an empty IP or to a device without SNMP the program throws […]

  49. gayathri Avatar
    gayathri

    Getting this error on executing this code. Please help at the earliest

    Exception in thread “main” java.lang.NullPointerException: Cannot invoke “org.snmp4j.PDU.get(int)” because the return value of “org.snmp4j.event.ResponseEvent.getResponse()” is null
    at com.mycompany.happy.happymain.getAsString(happymain.java:79)
    at com.mycompany.happy.happymain.main(happymain.java:53)
    Command execution failed.

  50. Vasanthan Avatar
    Vasanthan

    How can i install the SNMP server for windows11 and android phone?

  51. Halmat Avatar
    Halmat

    Exception in thread “main” java.lang.NullPointerException: Cannot invoke “org.snmp4j.PDU.get(int)” because the return value of “org.snmp4j.event.ResponseEvent.getResponse()” is null
    at SNMPManager.getAsString(SNMPManager.java:43)
    at SNMPManager.main(SNMPManager.java:29)

    is this problem solved???

    Although the linux computer and the windows computer are communicating, it gives this error…

  52. Eric Parayre Avatar
    Eric Parayre

    Hello Jitendra,
    Where can I find the “package com.G2.SNMP.client” and “package com.G2.SNMP”, and “package com.G2.SNMP.Server” libraries (sources and jar) ?
    If it is not provided, your code doesn’t compile.
    I’ve made a java project using 4 classes and I can’t progress any more.
    Please answer me ASAP because I’m in a job hurry.
    Thanks

    Eric

  53. Anil Avatar
    Anil

    Hi,
    Unable to download the libraries. it’s showing 404 error.

  54. Anil Kumar Avatar
    Anil Kumar

    Exception in thread “main” java.lang.NullPointerException
    at com.G2.SNMP.client.SNMPManager.getAsString(SNMPManager.java:54)
    at com.G2.SNMP.client.SNMPManager.main(SNMPManager.java:38)

    Getting above error. when I run the code.

Leave a Reply to gayathri Cancel 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.