Skip to main content

Create SNMP Client in JAVA Using SNMP4j

Please follow the below mentioned steps to write a very simple SNMP4J application using Java and eclipse IDE.

First you need to download a copy of SNMP4J.jar. You can get it from http://www.snmp4j.org/html/download.html

Then you need to decide how you are going to test your application. Check whether you have access to any real network devices like Cisco routers or Juniper routers or whether you are aware of any SNMP agent running on any of your servers.There is nothing to worry if you cannot find one , you can start SNMP agent on your desktop machine as well. Here I am giving an example of how you can use your Windows machine to test your application by starting the SNMP service on the machine.

I am using a Windows XP machine and below are the steps needed to start SNMP agent on the machine.

1. Go to Start->Control Panel -> Add or Remove Programs -> Add or Remove Windows Components
     Select or Check "Management and Monitoring Tools".


    This will start the SNMP Agent running on your windows machine.

2. Verify SNMP agent running on your machine
    Go to Start->Control Panel -> Administrative Tools->Services and verify the service. You can also add 
    new community strings for additional security here.


3. Now come to Java coding. Open a Java application project in Eclipse and add the SNMP4J.jar to the
    library path.

Below code is almost self explanatory. Please refer to http://www.snmp4j.org/doc/index.html for API reference. You are welcome with questions or comments.

Please note that I have tried snmpget on 'sysDescr' MIB on my Windows machine and got the output "
Hardware: x86 Family 6 Model 23 Stepping 10 AT/AT COMPATIBLE - Software: Windows 2000 Version 5.1 (Build 2600 Multiprocessor Free)". This is Cool.....




import java.io.IOException;
import java.util.Vector;
import org.snmp4j.CommunityTarget;
import org.snmp4j.PDU;
import org.snmp4j.Snmp;
import org.snmp4j.smi.*;
import org.snmp4j.mp.*;
import org.snmp4j.transport.DefaultUdpTransportMapping;
import org.snmp4j.event.ResponseEvent;
import org.snmp4j.util.*;
 

public class Collector
{
 
    public static void main(String[] args) {
        try {
            Snmp snmp4j =  new Snmp(new DefaultUdpTransportMapping());
            snmp4j.listen();
            Address add = new UdpAddress("192.168.1.132"+"/"+"161");
            CommunityTarget target = new CommunityTarget();
            target.setAddress(add);
            target.setTimeout(500);
             
            target.setRetries(3);

            target.setCommunity(new OctetString("public"));
            target.setVersion(SnmpConstants.version2c);
            
            PDU request = new PDU();
            request.setType(PDU.GET);
            OID oid= new OID(".1.3.6.1.2.1.1.1.0");
            request.add(new VariableBinding(oid));

            PDU responsePDU=null;
            ResponseEvent responseEvent;
            responseEvent = snmp4j.send(request, target);

            if (responseEvent != null)
            {
                responsePDU = responseEvent.getResponse();
                if ( responsePDU != null)
                {
                                
                    Vector <VariableBinding> tmpv = responsePDU.getVariableBindings();
                    if(tmpv != null)
                    {
                        for(int k=0; k <tmpv.size();k++)
                        {
                            VariableBinding vb = (VariableBinding) tmpv.get(k);
                            String output = null;
                            if ( vb.isException())
                            {

                                String errorstring = vb.getVariable().getSyntaxString();
                                System.out.println("Error:"+errorstring);
                            }
                            else
                            {
                                String sOid = vb.getOid().toString();
                                Variable var = vb.getVariable();
                                OctetString oct = new OctetString((OctetString)var);
                                String sVar =  oct.toString();

                                System.out.println("success:"+sVar);
                            }

                        
                    }
                    
                }

            }
            }

        } catch (IOException e) {
             
            e.printStackTrace();
        }

        

    }

}

Comments

  1. Hi,
    How to do this in ubuntu Os
    Regards
    Hari

    ReplyDelete
  2. Helo
    reply can any one give me answer for my above qus?

    ReplyDelete
    Replies
    1. Hi,

      The java program would work in Ubuntu as well but if your question is more like how to test it in Ubuntu OS then you need to install snmp on the machine.

      More details can be fould on this blog: http://wmunguiam.blogspot.com/2009/07/howto-install-snmp-and-test-snmpv1.html

      Delete
  3. Hi Mathew,
    Thanku for response.
    I have some question's regarding snmp4j ,( I am new snap and snmp4j).
    1.is it possible to connect X host to Y
    host.
    Thanks&Regards
    Hari.

    2. how to convert custom erros as a snmp traps and how send it X host to Y host.
    3.if possible what is the setup to do this.


    ReplyDelete
  4. Hi Mathew,
    1)Is it possible to send customized erros as a snmp traps from X host to Y host.. using snmp4j.?(i am new for snmp and snmp4j)
    2.if possible what setup needed here.?
    3.what type of information contains an snmp trap .
    4.suppose i have one web application this application aim is,
    The application gets the alerts(errors) data from the devices stores into local Db using web services .now if we want convert the these alerts data as an snmptrap .(is it possible to convert this using snmp4j)
    and sends these data from one host to another host.?
    Thanks&Regards
    Hari


    ReplyDelete
  5. Hi,
    Could respond my posts pls.

    ReplyDelete
  6. Hi,
    Thanks for the program,, can you help me..
    I want to list all the machine details(as the output of the above program) which are connected in my network...
    I am searching a long.. will you please give me an idea..

    ReplyDelete
  7. hello sir,
    it is showing error like error: incompatible types
    Vector tmpv = responsePDU.getVariableBindings();
    ^
    required: Vector
    found: Vector
    where CAP#1 is a fresh type-variable:
    CAP#1 extends VariableBinding from capture of ? extends VariableBinding
    1 error
    when compling
    can anybody pls help me

    ReplyDelete
    Replies
    1. change below line like this:
      Vector tmpv = (Vector ) responsePDU.getVariableBindings();

      Delete
  8. Please check and see whether you have SNMP4j.jar in your classpath.

    ReplyDelete
    Replies
    1. I cant solve the error adding SNMP4J.jar in classpath

      Delete
  9. Hi how can i do set with this please

    ReplyDelete
  10. The responseEvent.getResponse() returns null for me

    ReplyDelete
  11. I always appreciated your work, your creation is definitely unique. Great job

    apk editor pro|kahoot hack|www.myaarpmedicare.com|

    ReplyDelete

Post a Comment

Popular posts from this blog

How to format and install macOS in your old Macbook/ iMac

 You can follow these steps to install a mac OS on an old Mac book following these steps. Here I assume that you have the actual bootable CD for the OS for installation. 1. Restart the laptop 2. Press Command + R key until it shows recovery mode 3. Open Disk Utilities 4. Select the hard drive and try to partition the drive. For example I have created a partition called Partition1 5. Insert bootable CD and restart the laptop. When option comes choose to boot from the CD. 6. Choose partition1 as the place to install the OS 7. Continue the installation process. 8. Once installation is completed then it might need to restart for further updates. 9. Most of the times a more recent compatible version of the OS might be available. In order to upgrade to the more latest compatible OS follow below steps. 11. Find the latest compatible version of OS. 12. Go to apple support sites and manually download the image and click to install. 13. Follow installation instructions and this would upgrade you

How to create a minikube single node cluster for learning Kubernetes

In this post I will explain how to setup a minikube single node kubernetes cluster using AWS EC2 instance which would help anyone who is trying to learn kubernetes and also help them to gain practical knowledge in kubernetes by running kubernetes commands, creating kubernetes objects etc. Minikube is a single node kubernetes cluster which means a kubernetes cluster with only one node that is a single VM. Minikube is only used for learning purposes and it is not an alternative for a real kubernetes cluster and should not be used for development and production usage. In this example I have launched an AWS EC2 instance with below configuration where I will install minikube and related tools. AWS EC2 Instance Configuration AMI: Ubuntu Free tier eligible 64 bit Instance type : t2-large ( For me t2-small or t2-micro is giving performance issues due to less memory) Once the EC2 instance is up and running, login to the instance using below command on terminal. If you are using wi

log4j - How to write log to multiple log files using log4j.properties

In Java applications some times you may need to write your log messages to specific log files with its own specific log properties. If you are using log4j internally then first step that you need to do is to have a proper log4j.properties file. Below example shows 2 log4j appenders which write to 2 different log files, one is a debug log and another one is a reports log. Debug log file can have all log messages and reports log can have log messages specific to reporting on say splunk monitoring. # Root logger option log4j.rootLogger=ALL,STDOUT,debugLog log4j.logger.reportsLogger=INFO,reportsLog log4j.additivity.reportsLogger=false     log4j.appender.STDOUT=org.apache.log4j.ConsoleAppender log4j.appender.STDOUT.layout=org.apache.log4j.PatternLayout log4j.appender.STDOUT.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %C:%L - %m%n     # Direct log messages to a log file log4j.appender.debugLog=org.apache.log4j.RollingFileAppender log4j.appender.debugLo