Get all oid of network printer with snmp4j

I found a way to get all the oid I needed,

Instead of sending the snmp request with: ResponseEvent responseEvent = snmp.send(pdu, target);

You need to use: List<TreeEvent> events = treeUtils.getSubtree(target, new OID(tableOid)); that allows to fecth the OID subtree.

This is an example of the code I endup using:

public static Map<String, String> doWalk(String tableOid, Target target) throws IOException {

    String address = "udp:" + ip + "/161";
    String community = "public";        

    CommunityTarget target = new CommunityTarget();
    target.setAddress(GenericAddress.parse(address));
    target.setCommunity(new OctetString(community));
    target.setRetries(2);
    target.setTimeout(1500);
    target.setVersion(SnmpConstants.version2c);

    Map<String, String> result = new TreeMap<>();
    TransportMapping transport = new DefaultUdpTransportMapping();
    Snmp snmp = new Snmp(transport);
    transport.listen();

    TreeUtils treeUtils = new TreeUtils(snmp, new DefaultPDUFactory());
    List<TreeEvent> events = treeUtils.getSubtree(target, new OID(tableOid));
    if (events == null || events.size() == 0) {
        System.out.println("Error: Unable to read table...");
        return result;
    }

    for (TreeEvent event : events) {
        if (event == null) {
            continue;
        }
        if (event.isError()) {
            System.out.println("Error: table OID [" + tableOid + "] " + event.getErrorMessage());
            continue;
        }

        VariableBinding[] varBindings = event.getVariableBindings();
        if (varBindings == null || varBindings.length == 0) {
            continue;
        }
        for (VariableBinding varBinding : varBindings) {
            if (varBinding == null) {
                continue;
            }
             
            result.put("." + varBinding.getOid().toString(), varBinding.getVariable().toString());
        }

    }
    snmp.close();

    return result;
}

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top