How to implement an SNMP client in Java?

SNMP is the most widely used network management protocol. For more detail of SNMP, please refer to my previous post.

We can use SNMP4J to implement an SNMP client in Java. SNMP4J is an enterprise class free open source and state-of-the-art SNMP implementation for Java. SNMP4J provides us with a very clean API to interact with SNMP Agent.

The Snmp class is the core of SNMP4J. It provides functions to send and receive SNMP PDUs. All SNAMP PDU types can be send. Snmp class implements CommandResponder interface which means it can send PDUs synchronously and asynchronously.

SNMP client using SNMP4J:
`

public SNMPClient(String address) {
    this.address = address;
}

public static void main(String[] args) throws IOException {
    SNMPClient client = new SNMPClient("udp:192.168.56.1/161");
    client.start();

    String sysDescr = client.getAsString(new OID(".1.3.6.1.2.1.1.1.0"));
    System.out.println(sysDescr);
}

private void start() throws IOException {
    TransportMapping transportMapping = new DefaultUdpTransportMapping();
    snmp = new Snmp(transportMapping);
    transportMapping.listen();
}

public String getAsString(OID oid) throws IOException {
    ResponseEvent event = get(new OID[]{oid});
    return event.getResponse().get(0).getVariable().toString();
}

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 time out");
}

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;
}`

The OID of ".1.3.6.1.2.1.1.1.0" stands for iso.org.dod.internet.mgmt.mib-2.system.sysDescr, so above program will obtain the system description of the target system. I run it my notebook to get below output:

Hardware: Intel64 Family 6 Model 58 Stepping 9 AT/AT COMPATIBLE - Software: Windows Version 6.1 (Build 7601 Multiprocessor Free)

NOTE

  1. How to enable/install SNMP agent in window7, please refer to this article. In addition to that, actually, in order to make SNMP Agent works in windows, you still need to make a configuration in Windows service, please refer to this post for detail.

  2. There is a useful free tool to view the MIB structure of SNMP Agent named MIB Browser, you can download it from here.
    After you open the MIB Browser, you can also get the information of OID '.1.3.6.1.2.1.1.1.0' in above program, the search result is as below:

which is the same as the output of above program.

Written on 25 February 2016