Wednesday, December 17, 2008

Snmp4J - Java library for SNMP Communication...

We all know that if we need to use more on socket programming in java then we must use native code in c++.SNMP (Simple network Management Protocol) is used for communication with the network devices.Any network device can be queried using SNMP request.Snmp4j is the library which provides you implementation to make SNMP requests.

We can query any device (Switch,PC etc...) if it has a SNMP agent running,which will handle our SNMP request and respond with the proper data.This library made it so easy for us without looking into much details of SNMP.

In basic,SNMP is used for getting information (GET requests),but sometimes it can be used to set values in the device (SET requests).Assume that every device has a list of pre-defined variables in it,which are called OID(Object IDs).These OIDs will have a specific structure (which is called MIB file,which seems like a tree structured as in registry).

OID looks like 1.3.6.1.4.1.318.1.1.1.12.3.2.1.3.1, which has a special meaning.It has a description(name) and an associated value in it.When you query particular OID (i.e 1.3.6.1....),it will give its associated value.You can set its value also (if its allowed ;)).OIDs also have communities(Public,Private etc...) which shows permissions.Mostly public community is allowed to be viewed by SNMP requests.

See the example below how to make a SNMP request,
import org.snmp4j.*;

...
...

OctetString communityName = new OctetString("public");

String ipAddressUrl = strIpAddress+"/"+161; //161 is used for SNMP Agent...

Address targetAddress = new UdpAddress(ipAddressUrl);

TransportMapping transport = new DefaultUdpTransportMapping();

Snmp snmp = new Snmp(transport);

snmp.listen();

CommunityTarget target = new CommunityTarget();

target.setAddress(targetAddress);
target.setRetries(3);
target.setTimeout(500);

PDU pdu = new PDU();
pdu.setType(PDU.GET);

OID oid = new OID("1.3.6.1.2.1.1.");
VariableBinding vb = new VariableBinding(oid);

pdu.add(vb);
...
...

snmp.send(pdu, target);
So the last line, snmp.send(pdu, target), will return the SNMP4j Response having the value for OID we set in the PDU.This is just the example of how to get any data from OID.We can set the values using SET PDU.

0 Comments: