1.主要代码如下: 开发包(snmp4j.jar)
// 省略了导入的包
public class SnmpTest1 {
public static void main(String[] args) {
try {
Snmp snmp = new Snmp(new DefaultUdpTransportMapping());
snmp.listen();
CommunityTarget target = new CommunityTarget();
target.setAddress(GenericAddress.parse("udp:192.168.100.61/161"));
target.setCommunity(new OctetString("public"));
target.setTimeout(1000);
target.setRetries(2);
target.setVersion(SnmpConstants.version1);
PDU pdu = new PDU();
pdu.add(new VariableBinding(new OID("1.3.6.1.2.1.1.2.0")));
pdu.add(new VariableBinding(new OID("1.3.6.1.2.1.1.3.1")));
pdu.add(new VariableBinding(new OID("1.3.6.1.2.1.1.3.2")));
pdu.add(new VariableBinding(new OID("1.3.6.1.2.1.1.3.3")));
pdu.add(new VariableBinding(new OID("1.3.6.1.2.1.1.3.4")));
pdu.add(new VariableBinding(new OID("1.3.6.1.2.1.1.4.0")));
PDU newpdu = getSucPDU(snmp,target,pdu);
ResponseEvent event = snmp.get(newpdu, target);
PDU resp = event.getResponse();
for (int i = 0; i < resp.size(); i++) {
VariableBinding vb = resp.get(i);
System.out.println(vb.getOid().toString() +"^^^^"+ vb.getVariable());
}
} catch (IOException e) {
e.printStackTrace();
}
}
private static PDU getSucPDU(Snmp snmp, CommunityTarget target, PDU pdu) throws IOException {
ResponseEvent event = snmp.get(pdu, target);
PDU resp = event.getResponse();
int errorIndex = resp.getErrorIndex();
if(errorIndex != 0){
VariableBinding vb = resp.get(errorIndex -1);
OID errorOid = vb.getOid();
System.out.println(errorOid + ":" + resp.getErrorStatusText());
pdu.remove(errorIndex-1);
getSucPDU(snmp,target,pdu);
return pdu;
}
return null;
}
}
2. 运行结果为: