Ejemplo n.º 1
0
  private static void test2() throws IOException {

    DefaultUdpTransportMapping udpTransportMap = new DefaultUdpTransportMapping();
    udpTransportMap.listen();
    Snmp snmp = new Snmp(udpTransportMap);

    String address1 = "udp:192.168.0.104/161";
    String[] oids1 = new String[] {"1.3.6.1.2.1.2.2.1.10", "1.3.6.1.2.1.2.2.1.16"};
    List<String[]> l1 = getTable(snmp, address1, "public", SnmpConstants.version1, 1, oids1);
    for (String[] ss : l1) {
      for (String s : ss) {
        System.out.print(s + ",");
      }
      System.out.println();
    }

    System.out.println("/////////////////////////");
    ///
    String address2 = "udp:192.168.0.165/161";
    String[] oids2 = new String[] {"1.3.6.1.2.1.2.2.1.10", "1.3.6.1.2.1.2.2.1.16"};
    List<String[]> l2 = getTable(snmp, address2, "public", SnmpConstants.version1, 1, oids2);
    for (String[] ss : l2) {
      for (String s : ss) {
        System.out.print(s + ",");
      }
      System.out.println();
    }
  }
  /**
   * @param ip
   * @param community
   */
  public static void snmpGetList(String ip, String community, List<String> oidList) {
    CommunityTarget target = SnmpUtil.createDefault(ip, community);

    Snmp snmp = null;
    try {
      PDU pdu = new PDU();

      for (String oid : oidList) {
        pdu.add(new VariableBinding(new OID(oid)));
      }

      DefaultUdpTransportMapping transport = new DefaultUdpTransportMapping();
      transport.listen();
      snmp = new Snmp(transport);

      System.out.println("------->发送消息<-------");
      pdu.setType(PDU.GET);
      ResponseEvent respEvent = snmp.send(pdu, target);
      System.out.println("PeerAddress:" + respEvent.getPeerAddress());
      PDU response = respEvent.getResponse();

      if (response == null) {
        System.out.println("response is null, request time out");
      } else {
        System.out.println("response pdu size is " + response.size());
        for (int i = 0; i < response.size(); i++) {
          VariableBinding vb = response.get(i);
          System.out.println(vb.getOid() + " = " + vb.getVariable());
        }
      }
      System.out.println("SNMP GET List OID value finished !");
    } catch (Exception e) {
      e.printStackTrace();
      System.out.println("SNMP GetList Exception:" + e);
    } finally {
      if (snmp != null) {
        try {
          snmp.close();
        } catch (IOException ex1) {
          snmp = null;
        }
      }
    }
  }