Documente Academic
Documente Profesional
Documente Cultură
Table of Contents
Developing SNMPv2c Management Applications ................................................. 7 Choosing the Application Architecture.................................................................. 9
Overview............................................................................................................................ 10 Management Console Applications ................................................................................... 12 Middle-Tier Management Servers ..................................................................................... 13 Web Craft Interfaces.......................................................................................................... 15
Accessing Node Information.............................................................................................. 64 Retrieving MIB Information ................................................................................................ 66 Exceptions and Error Messages........................................................................................ 67 Database Schema ............................................................................................................. 73 Macro Type Constructs...................................................................................................... 77
AdventNet, Inc.
Handling Datatypes................................................................................................ 94
Overview............................................................................................................................ 95 SMI Datatypes ................................................................................................................... 99
Integer32...................................................................................................................................... 100 INTEGER (Enumerated) .............................................................................................................. 104 Unsigned32.................................................................................................................................. 108 Gauge32 ...................................................................................................................................... 111 Counter32 .................................................................................................................................... 115 Counter64 .................................................................................................................................... 119 Timeticks...................................................................................................................................... 124 OCTET STRING .......................................................................................................................... 128 OBJECT IDENTIFIER.................................................................................................................. 132 IpAddress..................................................................................................................................... 136 Opaque ........................................................................................................................................ 140 BITS ............................................................................................................................................. 141
AdventNet, Inc.
AdventNet, Inc.
AdventNet, Inc.
AdventNet, Inc.
Migration from 2.x to 4.0 .................................................................................................. 407 Low-Level API Changes .................................................................................................. 408 MIBs API Changes .......................................................................................................... 413
FAQs...................................................................................................................... 415
Beginners FAQs .............................................................................................................. 416 FAQs - General................................................................................................................ 420 FAQs - Bean Components............................................................................................... 424 FAQs - Low-Level API ..................................................................................................... 431 FAQs - MIBs API ............................................................................................................. 436 FAQs - SAS and Web Server .......................................................................................... 439 FAQs - EJB API ............................................................................................................... 441 FAQs - RMI API ............................................................................................................... 442 FAQs - CORBA API......................................................................................................... 444
Javadocs............................................................................................................... 445
AdventNet, Inc.
AdventNet, Inc.
FAQs includes the list of frequently asked questions that serve as a guide to understand AdventNet SNMP API. Javadocs contains the classes and methods pertaining to various modules of AdventNet SNMP API. It is meant for developers looking to build management applications and applets based on AdventNet SNMP API.
AdventNet, Inc.
AdventNet SNMP API can be used to develop Java and web-based network management applications and applets. Network management developers can use the AdventNet SNMP library to build servers, applications, applets, components, and distributed EJB, CORBA, and RMI applications. The library provides the most commonly used functions and components to make the development simpler. AdventNet SNMP API can be used for developing: Management Console Applications (Craft Interfaces) Middle-Tier Management Servers Web Craft Interfaces (Applets)
AdventNet, Inc.
Overview
Network management applications differ widely in the scope of their design, implementation, and deployment. Building such applications requires the understanding of many aspects of network management as well as software technologies. The management needs can be any of the following. Network management, system management, or device management Generic or customized management
The following are the types of applications that can be developed to meet the above-mentioned management needs. Embedded applications Operating system specific or cross-platform implementations Standalone applications Web-based applications and applets Distributed applications GUI or non-GUI (command line) applications Components used in other applications
The type of management application that needs to be developed largely depends on the purpose of the application. AdventNet SNMP API comes with the necessary APIs, which can help you in developing the applications of your choice.
AdventNet, Inc.
10
Types of Applications
In today's heterogeneous network environment, deciding on the type of applications becomes critical. The targeted customer base predominantly dictates the choice of the type of application. Most applications fall under any one of the following categories. Embedded applications - depend on the device. Most devices, such as switches, routers, and printers have embedded applications installed in it which can be used to manage the device. Operating system specific or cross-platform implementations - depend on the end user. If the end users use a particular operating system, the application can be developed pertaining to that OS. On the other hand, if multiple operating systems (Windows, Unix, or Macintosh) are used, it is better to develop the application that supports cross platform. In this case, a cross-platform language, such as Java should be used. Standalone applications - depends on customer needs and the managed device. These applications are implementation specific. Web-based applications and applets - This has the advantage of leveraging the Internet technologies. The application can be installed in a web server and the front end can access through the browser itself. This is implementation specific. Distributed applications - depend on users and managed devices. If the users or devices to be managed are distributed, distributed applications are required. Distributed applications can be developed using CORBA or RMI technologies.
Command-Line Applications
Command-line applications or tools are the simplest applications that can be developed for the SNMP management. Typically, these tools are used to send single request messages to the agent, receive responses, and display them in the console. These tools can also act as daemon process to receive and display traps. Command-line tools are normally used for fetching small amount of information, testing the MIB variables implemented by the agent, receiving debug information for a particular variable, testing whether a node is SNMP enabled, and so on. The usage of the command-line tools requires the user to have a good knowledge of SNMP. The user must understand the SNMP concepts such as community, OIDs, data types, SNMP errors, etc. in order to use the tools effectively.
GUI Applications
A simple command-line application has its limitations. After some time, it becomes complicated and tedious to use. Migrating to GUI environment gives the advantage of having an intuitive application with menu bars, toolbars, drag-and-drop components, graphs, and many more features.
AdventNet, Inc.
11
Management console applications provide the ability to manage and monitor all your network resources from a central location. The resources can be routers, switches, printers, or server applications. The management console can be used to perform the following operations. Configuration and tuning of device parameters Trending to study device performance Troubleshooting devices Alerts through emails and pagers under critical conditions
These applications can be built using the high-level or low-level AdventNet SNMP API. The high-level API has built-in UI and non-UI bean components, which makes the building of management console simple. Some of the bean components are as follows. SnmpTarget SnmpRequestServer - used for performing device configuration. SnmpTableModel - used to alter/configure SNMP tables graphically. SnmpPoller - used to perform trending of device parameters (such as network interface traffic) LineGraph, BarGraph - used to display the trending data graphically. SnmpTrapReceiver - used to receive traps or alerts from devices.
When the footprint of the management console has to be minimum, the low-level API can be used directly with MIBs support. Although the time taken to develop the application console is more when compared to using the high-level API, the low-level API can be used in applications where smaller footprint is required.
AdventNet, Inc.
12
Some of the benefits of the three-tier model are as follows. Scalability: The key benefit is improved scalability as the servers can be deployed on many machines and the processing can be distributed. And the back-end requires connection only from servers and not from every client. Re-usability: If the same kind of processing needs to be done by more than one client, the server can do the processing which can be used by all clients. This results in easy maintenance of code. Data integrity: All updates are done through the middle tier and therefore the middle tier can validate the data that is updated in the database. The clients do not have direct access to the database thereby eliminating the risk of a client corrupting the data. Reduced uploading time: Changes to business logic can be updated only on the servers resulting in easy maintenance and faster deployment.
AdventNet, Inc.
13
In the middle-tier architecture, AdventNet SNMP API can be used for: Data collection Status polling Network configuration
The client can use the distributed APIs of AdventNet, such as RMI and CORBA to access the middle tier. The back-end is the network from where the data is collected by the middle tier. Therefore the clients, the core APIs, and the network form a hybrid 3-tier model. Almost all the high-level APIs are supported from RMI and CORBA API. For building scalable NMS, the AdventNet APIs can be used in the middle tier and XML can be used for communication between the client and the server.
AdventNet, Inc.
14
Although applets are restricted from performing socket-related operations, AdventNet's SAS facilitates a full-featured applet interface. It can overcome the limitations imposed on applets by the Java security model. Therefore with AdventNet SNMP API and SAS, you can develop applets that can perform file operations, socket operations, and database queries.
AdventNet, Inc.
15
API Overview
High-Level API Architecture Low-Level API Architecture MIBs API Architecture SAS API Architecture RMI API Architecture CORBA API Architecture EJB API Architecture
This section explains the architecture of the different modules available as part of the AdventNet SNMP API distribution and the functions and features available with them.
AdventNet, Inc.
16
The following are the points to be noted while using the high-level APIs.
The non-UI beans, which uses the low-level API and MIBs, form the backbone of the high-level API and the UI beans are built on top of the non-UI beans.
AdventNet, Inc.
17
The following are the components available in the beans package that can be used in developing management applications or applets. SnmpTarget - for synchronous SNMP operations. SnmpRequestServer - for asynchronous SNMP operations. SnmpPoller - for polling SNMP data with specified polling intervals. SnmpTrapReceiver - for receiving traps. NotificationAdaptor - for using with TrapReceiver.
The above components are not user interface components. The following UI beans are provided in the ui package. SnmpTableModel is an extension of the SnmpTable component in the beans package and is designed for working with JFC-swing components. TableBean is an implementation of the combination of the JTable and the SnmpTableModel components, where JTable provides the view/controller and the SnmpTableModel is the model. SnmpTablePanel is a component for working with large tables. TrapParserBean is used for parsing the trap events. TrapBrowser is used to display the traps received by the TrapReceiver. TrapViewer is used to receive the traps and display the trap information. LineGraphBean is for plotting the polled data from SNMP data sources. MibTree is for viewing the SNMP MIBs in applets and applications. MibBrowser is an SNMP MIB browser that can be embedded in any management application or applet. PropertySettings is used for setting properties of other bean components. PropertyCombiner component is for passing one object from one bean to group of other beans. This is mainly used for setting properties of SNMP beans.
AdventNet, Inc.
18
The low-level API consists of the following functional modules. The SNMP transport provider framework provides a transparent layer for the communication classes to transport SNMP packets to devices over any protocol. API users can achieve this by plugging in their own protocol implementation or protocol provider into the framework. For example, transport providers for UDP, IPX, TCP, and Serial Port can be easily plugged into the framework. The API uses UDP/IP as the default underlying protocol for SNMP communication. A reference protocol provider implementation for TCP/IP has also been provided. The SNMP transport provider framework uses the configured protocol and is responsible for all communications between the manager and the agent. The Communication classes can be used to establish SNMP sessions with peer SNMP entities. The classes also provide APIs to set session parameters, such as the SNMP version, authentication parameters, and so on. These classes are the foundation on which the Java Beans components support and RMI/CORBA API support are built.
AdventNet, Inc.
19
The Variable classes correspond to the various SNMP data types, such as INTEGER, OBJECT IDENTIFIER, COUNTER, etc. Each of these classes has a one-to-one relationship with the SNMP data types. For example, the SnmpInt class corresponds to the INTEGER data type. You are required to work with these classes while sending requests and receiving responses. It is important that you are familiar with them, even if you are developing applications using the Java Beans components or RMI/CORBA components. Security API implements the procedures for providing the SNMP message level security and for controlling access to management information, in addition to defining the mechanism for remote configuration and administration of SNMPv3 entities. The AdventNet SNMPv3 security classes implement the two models USM and VACM based on the new security framework. Security and Access Frameworks API enables you to define and implement your own messagelevel security and access control.
AdventNet, Inc.
20
The MIB files may import some node information from other MIB modules. In such cases, the Parser automatically loads the imported module to get the information of objects imported from that particular module. For faster loading, the MIBs can be parsed and saved as .cmi files. The parsed MIB information can also be stored in the database or stored as serialized objects by using the API. The subsequent loading of the MIB file can be from the .cmi, database, or from serialized objects thus avoiding the parsing of the MIB file again. In the MIBParser, standard nodes and TCs defined in RFC1902 and SNMPv2-TC are predefined. Therefore, the MIBs that import these standard nodes or TCs can be loaded without loading the imported module.
AdventNet, Inc.
21
Applets can communicate with the SAS server through any protocol (TCP and HTTP implementations are provided). TCP is the default protocol used. HTTP can be used in case of communication across a firewall. The SAS API is built on top of a protocol-independent transport provider framework so that users can plug-in their own transport protocol implementations between the SAS client and the server. This would be required only if the protocol is other than TCP or HTTP (for example, SSL).
AdventNet, Inc.
22
The transport provider interfaces with the SNMP API to communicate between the client and the server. It essentially acts as a bridge between the SNMP API and the actual transport protocol. The advantage of using this approach is that the SNMP API need not be aware of the underlying protocol used. For using a particular protocol as the transport, the user has to implement that protocol and plug-in (or register) it with the transport provider. Only one transport protocol can register with the provider at a time.
AdventNet, Inc.
23
The RMI server can be started as a standalone server, or as part of another Java application, say a web server. The main interface or origin for all RMI operations is the com.adventnet.snmp.rmi.SnmpFactory interface. This interface is implemented by the com.adventnet.snmp.rmi.SnmpFactorImpl class, which can be started from the command line or from another Java application. When started from the command line, this class is published as AdventnetSnmpFactory and registered with the RMI registry. When started from another Java application, the user has to publish the factory interface to allow remote access. The SnmpFactory interface has methods for creating instances of classes for SNMP services on the server. These methods return RMI interfaces for getting access to the services provided by the SNMP service classes. These service interfaces very closely follow the SNMP beans classes in the com.adventnet.snmp.beans package. For example, this following code shows how the com.adventnet.snmp.rmi.SnmpTarget interface is obtained on a remote RMI client. String hostname = "myserver"; SnmpFactory factory = (com.adventnet.snmp.rmi.SnmpFactory) Naming.lookup( "rmi://" + hostname + "/AdventnetSnmpFactory" ); // Get an SnmpTarget object SnmpTarget target = factory.createTarget(); Once the com.adventnet.snmp.rmi.SnmpTarget interface is obtained, the RMI client can use its methods similar to a local instance of SnmpTarget. The method signatures between the corresponding beans and RMI interfaces are mostly identical.
AdventNet, Inc.
24
The following SNMP service interfaces are provided in the com.adventnet.snmp.rmi package. SnmpTarget SnmpRequestServer SnmpTrapReceiver SnmpPoller SnmpTable MibOperations
AdventNet, Inc.
25
There are sample client-side Java applications in the corbaclient directory that provide many of the SNMP operations with all direct SNMP API calls in snmpget are replaced with CORBA invocations.
AdventNet, Inc.
26
AdventNet, Inc.
27
The EJB does a JNDI look-up for the SnmpEJBServer, which permits clustering and load balancing of multiple SnmpEJBServer factories, when using clustering with the application server. Support for these capabilities vary with the particular application server being used. Typically, multiple SnmpEJBServer instances would be deployed on different servers, and using JNDI naming, the deployed EJBs will be load balanced over these SnmpEJBServer instances.
AdventNet, Inc.
28
This section explains the development environment needed for developing applications and applets using various APIs.
AdventNet, Inc.
29
AdventNet, Inc.
30
AdventNet, Inc.
31
AdventNet, Inc.
32
To run the rmiget client application example from a remote host, type the following command. java rmiget -SnmpServer SERVER:8001 localhost .1.3.6.1.2.1.1.1.0 It is assumed that the RMI SNMP server is running on a machine named "SERVER" on the port 8001 and you want the GET operation performed on SERVER itself. The argument "localhost" below specifies that GET operation is performed on the "localhost" as seen from the RMI SNMP server. To start the RMI applet example, type the following. appletviewer rmiAppletDemo.html You may need to edit the HTML file to point at the agent of your choice.
AdventNet, Inc.
33
The steps involved in developing management applications using CORBA interfaces and implementation classes are: 1. Run the Java IDL name server. tnameserv -ORBInitialPort serverport The above command starts the name server listening at the specified port. If the server port is not specified, the name server starts at the default port 900. tnameserv -ORBInitialPort 8000 The above command starts the name server listening at port 8000. 2. Start the AdventNet CORBA server. java com.adventnet.snmp.corba.server The above command binds the AdventNet CORBA server with the name server at the default port 900. If the AdventNet CORBA server starts successfully then the following message is displayed. "Factory is ready Server is ready Ready to receive client requests ... " 3. To start the CORBA server at different port, type the following command. java com.adventnet.snmp.corba.server -ORBInitialPort nameserverport e.g java com.adventnet.snmp.corba.server -ORBInitialPort 8000 The server class does the following on startup. //initialize the ORB org.omg.CORBA.ORB orb = org.omg.CORBA.ORB.init(args, null); //Create the "Factory" com.adventnet.snmp.corba.SnmpFactory factory = new com.adventnet.snmp.corba.SnmpFactoryImpl ("AdventnetSnmpFactory"); //Export to the ORB the newly created object orb.connect(factory); //Use Naming Service and bind the Object Reference in Naming
AdventNet, Inc.
34
The SnmpFactory interface has several methods, such as createRequestServer, createTable, createTarget, etc., and the corresponding destroy methods that are used by the client applications to create and destroy the respective instances after getting the remote object handle. The client applications need to do the following. 1. Initialize the ORB. org.omg.CORBA.ORB orb = org.omg.CORBA.ORB.init(args, null); 2. Use naming service. org.omg.CORBA.Object objRef = orb.resolve_initial_references("NameService"); 3. Narrow the object reference. NamingContext ncRef = NamingContextHelper.narrow(objRef); 4. Bind the object reference in naming. NameComponent nc = new NameComponent("AdventnetSnmpFactory", ""); NameComponent[] path = {nc}; 5. Bind to the factory object. com.adventnet.snmp.corba.SnmpFactory factory = com.adventnet.snmp.corba.SnmpFactoryHelper.narrow(ncRef.resolve(path)); 6. Get a target object. com.adventnet.snmp.corba.SnmpTarget target = factory.createTarget(); The above code creates an SnmpTargetImpl instance that internally calls the SnmpTarget bean. After this, the target instance can be used in the same way as in the high-level API. Note: Certain operations, such as target.loadMibs("../RFC1213-MIB"), are relative to the server path because the objects are remotely executed.
AdventNet, Inc.
35
These jar files conform to the EJB standards. The deployment procedure would be different for each EJB application server as there are wide range of EJB servers available in the market. The classes needed for EJB client to access the AdventNet SNMP API are provided in the com.adventnet.snmp.ejb package. The CLASSPATH should be set to AdventNet SNMP <classes> directory or the AdventNetEJB.jar Requirements The standard jar file available with AdventNet EJB API should also contain the weblogic-ejb-jar.xml file with the ejb-jar.xml file. For example, if the std_SnmpTargetEJB.jar is to be added to the WebLogic server, the jar file should contain the following in the package structure according to the EJB standards. SnmpTarget.class SnmpTargetEJB.class SnmpTargetHome.class ejb-jar.xml weblogic-ejb-jar.xml Note: The above example assumes that the EJB application server is BEA Weblogic Server 5.1. Go through the deployment procedure provided in the WebLogic documentation for more details.
AdventNet, Inc.
36
Management applications and applets need to perform MIB-related operations, such as loading and parsing of MIBs, accessing the nodes in a MIB tree, getting information from leaf nodes, and so on. The MIB support API (mibs package) in AdventNet SNMP API provides the necessary support to perform these kinds of MIB-related operations.
AdventNet, Inc.
37
Loading MIBs
Loading MIBs Directly Loading from Serialized Files Loading Compiled MIBs Loading from Database
AdventNet SNMP API provides flexible ways of loading MIBs in the applications. Management applications and applets can use any of the above options for loading the MIB modules. The MIB file can contain one or more MIB modules. The API loads all the dependency files to resolve the MIB module. The standard OIDs and TCs defined in RFC1155-SMI, RFC1212-SMI are already predefined in the API. If the MIB file imports any of the standard nodes defined in these two modules and the imported module is not present, the module is loaded. Therefore, it is optional to have a dependency file which has only the above-mentioned standard OID and TCs defined. In case of other nodes, when the imported file is not present or if the file does not contain the definition for that particular node, IMPORTS FAILED error is thrown.
AdventNet, Inc.
38
MIB
MibOperations
High Level
loadMibs(String)
AdventNet, Inc.
39
AdventNet, Inc.
40
The files set in the setMultipleRevision() method and the files that are loaded should be exactly the same. If the file set in the setMultipleRevison() method is with respect to the relative path and the file loaded is with respect to the absolute path, both the files are considered as different although the path of the files is the same. For example, if the file set is ../mibs/RFC1213-MIB.txt, and the file loaded is /home/mibs/RFC1213-MIB.txt, both these file names are considered as different and the module is loaded as RFC1213-MIB. The method getMultipleRevision() returns the multiple revision, if set. Otherwise it returns an empty string. The method isMultipleRevision() is used to know whether the multiple revision is set or not. Applications can use addLabel(String addLabel) to add a label that is not treated as a reserved word by the parser. For example, "DisplayString", "PhysAddress", "TestAndIncr", "TimeStamp", "MacAddress", "RowStatus", "TimeInterval" and "DateAndTime" are not treated as reserved words. If your MIB uses some of the standard textual conventions or reserved words as a label for the MIB node, you can use the addLabel() method to tell the parser not to treat it as a reserved word. For example, if you do not wish to treat UInteger32 as a reserved word while parsing your MIB, use the following code. MibOperations mibops = new MibOperations(); mibOps.addLabel("UInteger32"); try { mibops.loadMibModule("your-MIB"); } catch (Exception ex) { System.err.println("Error loading MIBs: " +ex); }
AdventNet, Inc.
41
The setSerializeMibs(boolean) method lets applications serialize the loaded MIBs. The following code shows how applications serialize a MIB module. MibOperations mibops = new MibOperations(); mibops.setSerializeMibs(true); try { mibops.loadMibModule("RFC1213-MIB"); } catch (Exception ex) { System.err.println("Error loading MIBs: "+ex); } The MIB modules are serialized in a file with the same name with an extension ser. For example, if the module name is RFC1213-MIB, the serialized file is created with the name RFC1213-MIB.ser. The setSerializedMibFileName(String) method can be used to specify the name of the serialized file. In the following code snippet, the loaded "RFC1213-MIB" module is serialized in the name of "myfilename". MibOperations mibops = new MibOperations(); mibops.setSerializedMibFileName("myfilename"); mibops.setSerializeMibs(true); try { mibops.loadMibModule("RFC 1213-MIB"); } catch (Exception ex) { System.err.println("Error loading MIBs: "+ex); }
AdventNet, Inc.
42
The setLoadFromSerializedMibs(boolean) method is used to specify that the MIB module should be loaded from the serialized file. If the serialized file is not present, the MIB file is parsed and the serialized file is created. Next time, the MIB file is loaded from the .ser file. MibOperations mibops = new MibOperations(); mibops.setLoadFromSerializedMibs(true); try { mibops.loadMibModule("RFC1213-MIB"); } catch (Exception ex) { System.err.println("Error loading MIBs: "+ex); } The serialization of the MIB module can be done even after the MIB file is loaded (except when it is loaded from a database). The option of loading MIB files as serialized files cannot be used with applets because of restrictions in file creation. However, we can load the already created serialized files in the applets. In that case the setLoadFromSerializedMibs(boolean) is set to true. By default, this method is set to false. If we have only the cmi file, we cannot use the serialized MIBs option. This is because we have no ser file or the original MIB file. In such cases, we can use the method, setSerializeMibs(true). This loads the MIB module from the cmi file and serializes it. After serializing, we can load this serialized file by setting setLoadFromSerializedMibs() to true. This method cannot be used if the MIB file is loaded from a database because the data is stored in the database and therefore the serialization is not possible. Note: If the MIB is loaded with the Serialized MIBs option with parsing level equal to or above NORMAL and if the MIB has errors, the serialized files will not be created.
AdventNet, Inc.
43
To store the compiled file information, the following file types are used. cmi - contains MIB information, such as name of a node, syntax, parent, sub-id, trap details, and textual conventions. cds - contains the description and reference of the nodes in the MIB.
For example for RFC1213-MIB, the compiled MIB files are RFC1213-MIB.cmi, and RFC1213MIB.cds. The setLoadFromCompiledMibs(boolean) method defines whether the MIB files can be loaded as compiled MIBs. By default, this value is set to false so that the user can directly load the MIB file as provided. When setLoadFromCompiledMibs() is set to true and the MIB file is loaded, the API loads the cmi and cds files. If these files are not present, the API parses the MIB file, writes the output to the cmi and cds files, and loads the MIB file as the compiled MIB file. Subsequent loading can be done by giving only the module name or <module name>.cmi. In both cases, the API loads the compiled MIB file. The advantage of using this option is that the MIB file need not be parsed each time it is loaded and the loading is thread safe. While loading compiled MIBs, it is sufficient to load only the cmi file. The cmi file has a reference to the cds files. The cds file should not be loaded directly. If the information in the cds file, such as description and reference is not required, we can set setReadDesc() to false. In this case, the parser loads only the cmi file and the loading is much faster.
AdventNet, Inc.
44
Note: After loading the MIB file as a compiled MIB file, if you modify the MIB file and load it again, the changes are not get reflected in the loaded MIB file. You have to remove the existing cmi and cds files and then load the MIB to get the changes reflected. The setOverwriteCMI(boolean) method in the MibOperations class can be used to overcome this restriction. By default, the value is set to false. If it is set to true, the cmi and cds files are created each time the MIB is loaded. Setting this boolean to true is recommended only if you have modified the MIB file. Otherwise, this will lead to unnecessary increase in the load time. The option of loading MIB files as compiled files cannot be used with applets because of restrictions in file creation. However, we can load the already created compiled files in the applets. In that case the setLoadFromCompiledMibs() is set to true. By default, this method is set to false. To convert the MIB files to the cmi and cds format, the MibToCMI utility can be used. This class is available in the AdventNetSnmp.jar. To use this utility, set the CLASSPATH to the classes directory and give the following command. java com.adventnet.snmp.utils.MibToCMI .. This conversion can be done for individual files or for entire directory. If the utility is used across directories, the existing cmi and cds files should first be deleted from the directory. We can also create compiled MIBs using the createCompiledMibs(String) MibOperations class. Note: The cmi file is dependent on the release version and the SNMP version. It is possible that a cmi file created in one version may not be loaded in another version and therefore the exception "Compiled Mib is corrupted" may be thrown. If the MIB is loaded with the compiled MIBs option with parsing level equal to or above NORMAL and if the MIB has errors, the cmi files will not be created. method in the
AdventNet, Inc.
45
Loading MIB files from a database gives the following advantages to applications. Scalability - database feature is particularly useful when the number of MIB files to be loaded are high. Applications can load hundreds of MIB files at a time. Memory Usage - Information is stored in the database and we cache only the referred node objects.
The performance of getting the node information using the database option is less than the other loading options without considering the network traffic. The API uses Java Database Connectivity (JDBC) for the database support. Applications should use a valid JDBC driver of the respective databases to enable the database support. To add database support for loading MIBs, applications should first initialize the necessary database parameters. The initJdbcParams(driverName, URL, userName, passWord) method is used for initializing the database parameters. The following are the arguments of the method. driverName - Name of the database driver URL - URL pointing to the database userName - Name of the user passWord - Password for the user
After initializing the database parameters, the value of the setLoadFromDatabase(boolean flag) method is set to true to enable the database support. By default, the value is set to false.
AdventNet, Inc.
46
When setLoadFromDatabase() is set to true and loadMibModules(String fileNames) is called, the application loads the MIB file from the database. If the MIB files are not present in the database, the MIB files are loaded in the database and then loaded in the application. After loading the MIB files from the database, if any changes are made to it and loaded again, the changes will not be reflected in the loaded MIB file. The MIB files in the database need to be overwritten. The method setOverwriteDatabase(boolean overWrite) defines whether to overwrite the existing database files. The other methods related to database operations are: isOverwriteDatabase() isLoadFromDatabase() - Gets the overwriteDataBase boolean method. - Gets the loadFromDatabase boolean method.
The method setDatabaseName(byte type) is used to set the database. The APIs are tested using the MySql and Oracle databases. The default database is MySql. If you want to set the database to Oracle, the type is set as MibOperations.ORACLE. In case of loading MIBs from a database other than MySql in overwrite option, the method setDatabaseName(byte type) in the MibOperations class should be called before loading the MIBs. Otherwise java.sql.SQLException is thrown.
The jar file mysql_comp.jar is to be included in the CLASSPATH. If the jar is not in the CLASSPATH, the following exception is thrown. Java.lang.ClassNotFoundException org.gjt.mm.mysql.Driver
The oracle driver is to be included in the CLASSPATH. If the jar is not in the CLASSPATH, the following exception is thrown. Java.lang.ClassNotFoundException oracle.jdbc.driver.OracleDriver For other databases, use the equivalent parameters.
AdventNet, Inc.
47
Unloading MIBs
When a MIB module is unloaded, it dereferences all the node information corresponding to the unloaded module. When the MIB file is loaded again, a new reference for the MIB module is created. The MIB module is unloaded only if it is present in the module list. The method unloadMibModule(MibModule module) is used to unload the MIB module, given the MibModule instance. The method unloadMibModule(String name) is used to unload MIB module by giving the name of the module, if present. Otherwise, it returns null. The method unloadAllMibModules() is used to unload all the MIB modules loaded in a MibOperations instance.
AdventNet, Inc.
48
Parsing MIBs
Parsing Levels Checks for Various Parsing Levels Checks in Detail
This section explains the parsing and validating the syntax of the MIB module and constructing the MIB module into the tree structure. A detailed description of the different levels of parsing that can be set and their corresponding checks are also discussed in this section.
AdventNet, Inc.
49
Parsing Levels
Applications, while loading MIB files, perform the following operations. Parsing and validating the syntax of the MIB module Constructing the MIB module into the tree structure
While performing the parsing and validation of the MIB files, if the MIB modules fail to conform to the SMI standards the loading will not be not done. However, the application requirements might mandate the loading of the non-standard files. On the other hand, some applications might require a stricter check on the compliance to the standards. The parsing and validating the syntax of the MIB file can be made configurable to suit the application requirements. AdventNet SNMP API handles this by providing the following set of parsing levels which facilitates to select the level of parsing required by the applications. Lenient Normal Serious Critical
In addition to the above four parsing levels, SNMP API supports another level, which is user-defined. In case of user-defined level, you can define your own parsing level with the required checks at runtime. The code snippet for setting the parsing level is as follows. MibOperations mibOps = new MibOperations(); mibOps.setParsingLevel(MibOperations.SERIOUS); try { loadMibModules(fileName); } catch(Exception ex) { System.out.println(ex.getMessage()); } The various parsing levels are defined in the following constants. MibOperations.LENIENT MibOperations.NORMAL MibOperations.SERIOUS MibOperations.CRITICAL
In the applications, parsing level has to be set first before loading a MIB. This level, once set, is used for subsequent MIBs that are loaded. If the level needs to be modified for the next set of MIBs loaded, it has to be set again. The parsing level can be set for the dependency file also. This can be done by using the method setImportsParsingLevel(byte parsingLevel). To get the parsing level of an imported MIB file, you need to use the getImportsParsingLevel() method. In addition, checks can be added or removed from a parsing level by using the methods addChecks(byte[] checks, byte parsingLevel) and removeChecks(byte[] checks, byte parsingLevel) respectively. The getChecks(byte parsingLevel) method retrieves all the checks of the specified parsing level. If there are any errors in the macro constructs, a parser exception is thrown. The getErrorModuleNames() returns a vector of modules names, which contain the parsing errors. The
AdventNet, Inc.
50
getErrorMessages(String module) returns a vector of MibErrorMessages object, which contains the error code, general error message associated with the parsing error, and a vector of ErrorObject objects. The object ErrorObject contains line number and the column number of the error messages and specific errors. Note: It is recommended to use the higher parsing level (SERIOUS, CRITICAL) for validating the MIB file and not for loading the MIB file in the application. It affects the performance of the application while loading the MIB files, because it takes considerable amount of time and resources, such as memory, CPU usage etc.
AdventNet, Inc.
51
Serious
Critical
When the parsing level is Lenient (default parsing level), none of the above checks are done. Besides the above mentioned parsing levels, you can choose your own parsing level with the required checks. The method registerParsingLevel(byte[] checks, byte parsingLevel) in the MibOperations class can be used for configuring a new parsing level. If any of the parent check is enabled, the corresponding child checks are done. To construct a new parsing level that contains checks for validating the OBJECT-TYPE construct, you can do the following.
AdventNet, Inc.
52
byte[] object_type_checks = new byte[1]; object_type_checks[0] = MibParserConstants.OBJECT_TYPE_CONSTRUCT mibOperations.registerParsingLevel((byte)5, object_type_checks); Note that the new parsing level should be registered with byte values other than 0, 1, 2, and 3. If you want to add a check to an existing parsing level or remove a check from an existing parsing level, you can use the methods addChecks() and removeChecks(). To add the check CHECK_IDENTIFIERS (Critical level) to Serious parsing level: byte[] iden_checks = new byte[1]; iden_checks[0] = MibParserConstants.CHECK_IDENTIFIERS miboperations.addChecks(iden_checks, MibOperations.SERIOUS); To remove the check TRAP_TYPE_CONSTRUCT from the Serious parsing level: byte[] remChecks = new byte[1]; remChecks[0] = MibParserConstants.TRAP_TYPE_CONSTRUCT miboperations.removeChecks(remChecks, MibOperations.SERIOUS); You can set the different parsing level for the IMPORTS MIB file by using the setImportsParsingLevel(byte parsingLevel) method. There are some rules that a MIB file should follow, without which the MIB tree is not formed properly. When the parser encounters such violations, MibException is thrown. The OID construct should contain atleast two suboids. The second and its subsequent suboids should be number or nameNumber to identify their ancestors and their position in the MIB tree. In the OBJECT_IDENTIFIER construct, if the first suboid is a number, it should be 0. 1, or 2. If the suboid is a name Number, it should be ccit(0), iso(1), or joint-iso-ccit(2). The label of the last suboid should be same as the descriptor. The maximum value of the sub-identifier cannot exceed 4294967295. The table entry should be defined as a child of the corresponding table object. The module name of the MIB file should start with uppercase letter. The TC name should not start with lowercase letter.
Therefore, the following checks are done even when the parsing level is set to lenient. These checks are termed as "Very Critical Checks" and are done irrespective of the parsing level. CHECK_ATLEAST_TWO_SUBOID CHECK_SECOND_SUBOID CHECK_FIRST_SUBOID CHECK_LAST_SUBOID CHECK_LONG_SUBOID CHECK_TABLE_OBJECT VALIDATE_MODULE_NAME VALIDATE_TC_NAME
AdventNet, Inc.
53
Checks in Detail
The checks are based on the Imports, macro constructs, and some miscellaneous specifications of the MIB file. All the checks are grouped with the parent checks. Parent Checks o o o o o o o o o o o o o o o o o OBJECT_IDENTIFIER_CONSTRUCT CHECK_DEFAULT IMPORTS_CONSTRUCT MODULE_IDENTITY_CONSTRUCT OBJECT_TYPE_CONSTRUCT TRAP_TYPE_CONSTRUCT NOTIFICATION_TYPE_CONSTRUCT TEXTUAL_CONVENTION_CONSTRUCT AGENT_CAPABILITIES_CONSTRUCT OBJECT_GROUP_CONSTRUCT MODULE_COMPLIANCE_CONSTRUCT CHECK_IDENTIFIERS CHECK_DEFVAL CHECK_TABLE_CONSTRUCT CHECK_SYNTAX CHECK_ACCESS CHECK_MISCELLANEOUS OBJECT_IDENTIFIER_CONSTRUCT CHECK_DEFAULT IMPORTS_CONSTRUCT MODULE_IDENTITY_CONSTRUCT OBJECT_TYPE_CONSTRUCT TRAP_TYPE_CONSTRUCT NOTIFICATION_TYPE_CONSTRUCT TEXTUAL_CONVENTION_CONSTRUCT AGENT_CAPABILITIES_CONSTRUCT OBJECT_GROUP_CONSTRUCT MODULE_COMPLIANCE_CONSTRUCT CHECK_IDENTIFIERS CHECK_MISCELLANEOUS
Normal Checks o o
Serious Checks o o o o o o
Critical Checks o o o o o
AdventNet, Inc.
54
Normal Checks
OBJECT_IDENTIFIER_CONSTRUCT In the OID construct the second suboid should be a CHECK_SECOND_SUBOID name or nameNumber. The OBJECT IDENTIFIERS should have atleast two CHECK_ATLEAST_TWO_SUBOID sub-identifiers. In the OBJECT IDENTIFIER construct, the first subidentifier should be any one of the following. CHECK_FIRST_SUBOID Value 0 1 2 Name ccitt iso joint-iso-ccitt
CHECK_LAST_SUBOID CHECK_LONG_SUBOID
In the OID construct, the label of the last sub-oid should be same as the descriptor. In the OID construct, the numbered suboid value should not exceed 4294967295. CHECK_DEFAULT The following are reserved keywords which must not be used as descriptors or module names: ABSENT ACCESS AGENTCAPABILITIES ANY APPLICATION AUGMENTS BEGIN BIT BITS BOOLEAN BY CHOICE COMPONENT COMPONENTS CONTACT-INFO CREATIONREQUIRES Counter32 Counter64 DEFAULT DEFINED DEFINITIONS DEFVAL DESCRIPTION DISPLAYHINT END ENUMERATED ENTERPRISE EXPLICIT EXPORTS EXTERNAL FALSE FROM GROUP Gauge32 IDENTIFIER IMPLICIT IMPLIED IMPORTS INCLUDES INDEX INTEGER Integer32 IpAddress LAST-UPDATED MANDATORYGROUPS MAX MAX-ACCESS MIN MIN-ACCESS MINUS-INFINITY MODULE MODULE-COMPLIANCE MODULE-IDENTITY NOTIFICATION-GROUP NOTIFICATION-TYPE NOTIFICATIONS NULL OBJECT OBJECT-GROUP OBJECTIDENTITY OBJECT-TYPE OBJECTS OCTET OF OPTIONAL ORGANIZATION Opaque PLUSINFINITY PRESENT PRIVATE PRODUCT-RELEASE REAL REFERENCE REVISION SEQUENCE SET SIZE STATUS STRING SUPPORTS SYNTAX
CHECK_RESERVED_WORDS
AdventNet, Inc.
55
CHECK_DEFAULT TAGS TEXTUAL-CONVENTION TRAP-TYPE TRUE TimeTicks UNITS UNIVERSAL Unsigned32 VARIABLES VARIATION WITH WRITE-SYNTAX In the SEQUENCE construct, each sequence member should be separated by a comma and there should not be a comma at the end CHECK_PROPER_FIELDS of last sequence member. In the GROUPS construct, the SYNTAX, WRITE-SYNTAX, MINACCESS clauses are not allowed. The descriptor should be unique CHECK_MULTIPLE_OCCURRENCE_OF_NODE and mnemonic. The identifier for the TEXTUALVALIDATE_TC_NAME CONVENTION should start with uppercase letter. The labels used in the enumeration CHECK_MULTIPLE_OCCURRENCE_OF_ENUM_LABEL list should be unique. The table entry must present immediately beneath the corresponding table object. i.e., The CHECK_ROW_OBJID table entry object should be the child of the table object with sub identifier as "1". The table entry should be defined CHECK_TABLE_OBJECT as a child of the corresponding table object. An ASN.1 module name should begin with an upper-case letter and continues with zero or more letters, VALIDATE_MODULE_NAME digits, or hyphens, except that a hyphen can not be the last character, nor can there be two consecutive hyphens.
Serious Checks
IMPORTS_CONSTRUCT The following must not be included in an IMPORTS statement. CHECK_INVALID_IMPORTS_VALUES Named types defined by ASN.1 namely INTEGER, OCTET STRING, OBJECT IDENTIFIER, SEQUENCE, SEQUENCE OF. The BITS construct.
CHECK_EXPORT_CONSTRUCT
CHECK_CONSTRUCT_IN_IMPORTS
The EXPORTS statement is not allowed in an SMIv2 MIB. All the items defined in a module is automatically imported. If any of the following datatypes and macros are defined in this document, they must be imported using the IMPORTS statement. Counter32, Counter64, Gauge32, Integer32,
AdventNet, Inc.
56
IMPORTS_CONSTRUCT IpAddress, MODULE-IDENTITY, NOTIFICATIONTYPE, Opaque, OBJECT-TYPE, OBJECTIDENTITY, TimeTicks, Unsigned32 In an SMIv2 MIB, if the IMPORTS section contains INVALID_IMPORTS_IN_V2 RFC1155-SMI, it should be replaced by SNMPv2SMI. MODULE_IDENTITY_CONSTRUCT There must be only one MODULE-IDENTITY CHECK_MODULE_IDENTITY_INVOCATION macro defined in the MIB. The MODULE-IDENTITY macro must be CHECK_MODULE_IDENTITY_OCCURRENCE defined immediately after the IMPORTS section. The REVISION clause should be defined in REVERSE_CHRONOLOGICAL_ORDER the revers chronological order. i.e. the latest revision should occur first. The UTCTime format is YYMMDDHHMMZ or YYYYMMDDHHMMZ. It should contain 11 or 13 characters. where YY - last two digits of year (only years between 1900-1999) YYYY - last four digits of the year (any year) MM - month (01 through 12) DD - day of month (01 through 31) HH - hours (00 through 23) MM - minutes (00 through 59) Z - denotes GMT (the ASCII character Z) For example, "9502192015Z" and "199502192015Z" represent 8:15pm GMT on 19 February 1995. Years after 1999 must use the four digit year format. Years 1900-1999 may use the two or four digit format." The UTC Time value mentioned in the LASTUPDATED field should be same as the UTC Time value in the first of the REVISION field.
CHECK_UTC_TIME
CHECK_LUPDATED_REVISION_UTC_TIME
OBJECT_TYPE_CONSTRUCT The following are the checks that fall under OBJECT_TYPE_CONSTRUCT. CHECK_DEFVAL, CHECK_TABLE_CONSTRUCT, OBJECT_TYPE_CONSTRUCT CHECK_SYNTAX, CHECK_ACCESS, CHECK_STATUS These are parent checks, which in turn include many checks. TRAP_TYPE_CONSTRUCT The trap number should range between CHECK_TRAP_NUMBER 0..2148473647. If the trap is generic, the trap number should be CHECK_GENERIC_TRAP_NUMBER between 0 to 6. If the enterprise value is other than snmp, the value CHECK_ENTERPRISE_VALUE should be registered under enterprise OID (.1.3.6.1.4.1).
AdventNet, Inc.
57
NOTIFICATION_TYPE_CONSTRUCT For the NOTIFICATION-TYPE macro, the objects CHECK_NT_OBJECTS_ACCESS should not have an MAX-ACCESS value of 'notaccessible'. TEXTUAL_CONVENTION_CONSTRUCT The DISPLAY-HINT clause must not be present if the Textual Convention is defined with any of the following syntax. OBJECT CHECK_OCCURRENCE_OF_DISPLAY_HINT IDENTIFIER, IpAddress, Counter32, Counter64 or any enumerated syntax (BITS or INTEGER). The standard format for DISPLAY-HINT is as follows. INTEGER Format: <intDisplayHint> = "d" ["-" number]|<singleChar> <singleChar> = o|x|b OCTET STRING Format: <octetDisplayHint> = <octDisplaySpec> <octDisplaySpec> = number <displayFormat> [<sepChar>] | "*" number <displayFormat> [<sepChar> [<repTermChar>]] <displayFormat> = "d" | "b" | "o" | "x" number - unsigned integer <sepChar> - separator character, any character except "*" and decimal digit <repTermChar> - repeat terminator character: any character other than "*" and decimal digit. The SYNTAX clause of a Textual Convention can not refer to a previously defined Textual Convention. The syntax could be any one of the following SNMP datatypes with possible sub-typing: INTEGER, OCTET STRING, OBJECT IDENTIFIER, Integer32, IpAddress, Counter32, Gauge32, Unsigned32, TimeTicks, Opaque, and Counter64.
CHECK_DISPLAY_HINT_FORMAT
CHECK_TC_AS_SYNTAX
Critical Checks
AGENT_CAPABILITIES_CONSTRUCT The CREATION-REQUIRES clause must not be present unless the object named in CHECK_CREATION_REQUIRES the correspondings VARIATION clause is a conceptual row. All objects which are named in the CHECK_ACCESS_FOR_CREATION_REQUIRES CREATION-REQUIRES clause must have an access level of "read-create".
AdventNet, Inc.
58
OBJECT_GROUP_CONSTRUCT The objects defined in the OBJECT-GROUP CHECK_OBJECTS_IN_THIS_MODULE macro should be defined in the same module where this OBJECT-GROUP is defined. The MAX-ACCESS value of the objects defined in the OBJECTS clause must be one of the following. accessible-for-notify CHECK_OBJECTS_ACCESS read-only read-write read-create The objects defined in the OBJECTS clause CHECK_INVALID_OBJECTS should not start with upper case. MODULE_COMPLIANCE_CONSTRUCT A MIN-ACCESS clause should not be present for CHECK_MIN_ACCESS_CONSTRUCT 1. columnar objects 2. objects with syntax as Counter32 or Counter64. A group named in a GROUP clause must not be CHECK_MANDATORY_GROUPS the one defined in the corresponding MANDATORY-GROUPS clause. The access value specified in the MIN-ACCESS clause must not be greater than is specified in the CHECK_MIN_MAX_ACCESS MAX-ACCESS clause of the OBJECT-TYPE macro. In the MODULE-COMPLIANCE construct, if the CHECK_OBJECTS_IN_MC MODULE clause doesn't contain any moduleName, the objects should be defined in this module. CHECK_IDENTIFIERS The hyphen are not allowed for an ASN.1 identifier (except for use by information CHECK_HYPHEN_IN_IDENTIFIERS modules converted from SMIv1 which did allow hyphens). The descriptor should not exceed 64 CHECK_NO_OF_CHARACTERS_EXCEEDS_64 characters in length. The descriptor should not exceed 32 CHECK_NO_OF_CHARACTERS_EXCEEDS_32 characters in length. The convention for the naming of the table object is: The table name should start with lowercase letter and it should ends with "Table". The SEQUENCE object name should be same as the table name except, the initial lower case letter should be converted into upper case letter. The word "Table" should be replaced with the word "Entry". The table entry name should be same as the SEQUENCE name but the initial upper case letter should be converted into lower case letter. For example, table name: ifTable SEQUENCE name: IfEntry entry name : ifEntry
CHECK_TABLE_NAMING_CONVENTION
AdventNet, Inc.
59
CHECK_LC_NAME
CHECK_ENUM_LABEL
CHECK_TC_CASE VALIDATE_SEQUENCE_NAME
CHECK_IDENTIFIERS The descriptors/identifiers for the following macros should not start with upper case letter. OBJECT-TYPE, NOTIFICATION-TYPE, NOTIFICATION-GROUP, OBJECT-GROUP, MODULE-COMPLIANCE, AGENTCAPABILITIES TRAP-TYPE, OBJECTIDENTITY, MODULE-IDENTITY The labels used in the enumeration list should not start with upper case or number and it should not contain hyphen. The descriptor for the TEXTUALCONVENTION should not consist of all upper case letters. The descriptor for the SEQUENCE construct should start with upper case.
CHECK_DEFVAL The binary value should contains zeros and ones. The value should contain eight digits and CHECK_BINARY_DEFVAL should be enclosed within single quotes and should end with 'b 'or 'B'. The hex defval should contain even number of CHECK_HEX_DEFVAL digits. The value should be enclosed in single quotes and should end with 'h' or 'H'. The DEFVAL clause should not be present for CHECK_DEFVAL_FOR_COUNTER_SYNTAX the nodes whith syntax Counter/Counter32 and Counter64. For the nodes with syntax as OBJECTCHECK_OID_OIDY_DEFVAL IDENTIFIER, the value of the DEFVAL clause should be an OBJECT-IDENTITY macro. For the nodes with syntax as OBJECT IDENTIFIER, the DEFVAL clause value should be: 1. defined in this module or imported from any CHECK_INVALID_OID_DEFVAL other MIB module. 2. expressed as a single ASN.1 identifier, and not as a collection of sub-identifiers. The value of the DEFVAL clause must correspond to the SYNTAX clause for the VALIDATE_DEFVAL object. Also, the default value should not contradict the range/values specified in syntax for a particular variable. CHECK_TABLE_CONSTRUCT The number of nodes defined in the SEQUENCE construct should be same as the number of nodes actually defined. Also the syntax defined in the CHECK_SEQUENCE_CONSTRUCT SEQUENCE construct should not contradict with the syntax in the node definition. The index nodes cannot have the syntax CHECK_INDEX_NODE_SYNTAX Counter/Counter32 and Counter64. The node entry defined in the CHECK_RECURSIVE_AUGMENTS_CONSTRUCT AUGMENTS clause should not contains AUGMENTS clause.
AdventNet, Inc.
60
CHECK_TABLE_CONSTRUCT The SEQUENCE construct should CHECK_COLUMNAR_NODES contain atleast a single node which is not auxillary. The index node should not repeat in the CHECK_OCCURRENCE_OF_INDEX_NODE same INDEX clause. Atleast a single node in the SEQUENCE CHECK_OCCURRENCE_OF_ROWSTATUS_NODE construct should have RowStatus as syntax. In the INDEX clause, the IMPLIED CHECK_OCCURENCE_OF_IMPLIED_NODE keyword should be present only for the last node. In the INDEX clause, the IMPLIED keyword should be present only for the CHECK_IMPLIED_NODE_TYPE node with syntax as OCTET STRING with variable length or OBJECTIDENTIFIER. The node present in the AUGMENTS CHECK_ENTRY_IN_AUGMENTS_CONSTRUCT construct should be a table entry. The subtyping information should not be CHECK_SEQUENCE_WITH_SUBTYPE present for the nodes present in the SEQUENCE construct. CHECK_FOR_SCALAR_INDEX The index node must not be scalar. The usage of the following named SMI types in the INDEX clause is allowed only in SMIv1 MIB. INTEGER OCTET STRING CHECK_INDEX_VALUE OBJECT IDENTIFIER NetworkAddress IpAddress These index values are not supported in SMIv2. CHECK_SYNTAX The BITS value should be contiguous starting from 0 and if not contiguous, the next bit value should be multiple of eight (for e.g. 0,1,2,3,8,9,.). Although there is no SMI-specified limitation on the number of enumerations there may be implementation and interoperability limitations for sizes in excess of 128 bits. The enumerated value should not be present for the Integer32 type. For any object with an integer-valued SYNTAX clause, in which the corresponding INTEGER does not have a range restriction the object MUST have the value of the SYNTAX clause changed to Integer32, or have an appropriate range specified. If any object has a SYNTAX clause value of Counter, the object MUST have the value of its SYNTAX clause changed to
CHECK_BITS_VALUE
CHECK_ENUM_IN_INTEGER32
CHECK_INVALID_V2_SYNTAX
AdventNet, Inc.
61
CHECK_SYNTAX Counter32. If any object has a SYNTAX clause value of Gauge, the object MUST have the value of its SYNTAX clause changed to Gauge32, or Unsigned32 where appropriate. The syntax "NetworkAddress" should not CHECK_NETWORK_ADDRESS be used in an SMIv2-MIB. If the OCTET STRING syntax contains CHECK_FOR_SIZE_CLAUSE_IN_OCTET_STRING subtyping information, the SIZE clause must be present. The enumerated value start at 1 and must be numbered continuously. If the syntax of the objects defined in the CHECK_ZERO_IN_ENUM INDEX clause is enumerated Integer, the zero should not be used as an enumerated value. The SIZE clause should not be present CHECK_FOR_SIZE_CLAUSE_IN_INTEGER for the INTEGER and Integer32 syntax. In case of multiple ranges, the range CHECK_RANGE_INTERSECTION values should not overlap. The range definition (0..100 | 50..150) is invalid. The range values should be unique. The range values should not duplicate. In the CHECK_RANGE_DUPLICATION range definition (0..100 | 150 | 200..250 | 150). The value '150' is defined twice. The sub-typing information should not be present for the following syntax. CHECK_SUBTYPING_FOR_SYNTAX OBJECT IDENTIFIER, IpAddress, Counter32, Counter64 and TimeTicks. The size of the OCTET STRING should CHECK_SIZE_FOR_OCTET_STRING not exceed 65535. The negative values should not be used CHECK_NEGATIVE_VALUE_IN_SIZE in the range definition. The keyword MAX and MIN should not be CHECK_MAX_MIN_RANGE used in the range definitions. The Opaque type is provided solely for CHECK_OPAQUE_SYNTAX backward-compatibility, and shall not be used for newly-defined object types. CHECK_ACCESS If the syntax of the node is Counter/Counter32 or Counter64, the CHECK_ACCESS_FOR_COUNTER_SYNTAX access value should be either 'read-only' or 'accessible-for-notify'. If the syntax of the node is RowStatus, CHECK_ROWSTATUS_ACCESS the access value should be read-create. In a conceptual row, if any of the node has read-create as its access value, no CHECK_ACCESS_FOR_COLUMNAR_NODES other node in the same row can have the access value as read-write. The SMIv1 access value "notCHECK_ACCESS_VALUE implemented" should not be used in an SMIv2 module.
AdventNet, Inc.
62
CHECK_ACCESS The access value for the table and table CHECK_ACCESS_IN_TABLE_AND_ENTRY_NODE entry should be 'not-accessible'. The access value for the index nodes CHECK_INDEX_NODE_ACCESS should be 'not-accessible'. CHECK_STATUS The STATUS values for the SMIv2 MIB modules are current deprecated obsolete.
CHECK_STATUS
CHECK_MISCELLANEOUS The object identifier value should not be placed between the module name and the "DEFINITIONS" keyword." CHECK_OID_BETN_MODNAME_DEFINITIONS TEST-MIB { iso org(3) dod(6) internet(1) private(4) enterprises(1) 2186} DEFINITIONS ::= BEGIN This is invalid. The ASN comments (--) should not be CHECK_COMMENTS_IN_TEXT present inside the quoted String. The SMIV1 keyword ACCESS should not be CHECK_ACCESS_KEYWORD used in an SMIv2 MIB. It should be replaced by MAX-ACCESS. The conceptual row should contain no more CHECK_NUMBER_OF_COLUMNAR_NODES than approximately 20 objects. The DEFVAL value should be present within CHECK_BRACES_IN_DEFVAL the braces. The value in the DEFVAL field should not be CHECK_EMPTY_DEFVAL empty. The SMIv1 macros must not be used in CHECK_FOR_SMIV1_CONSTRUCT SMIv2 information modules.
AdventNet, Inc.
63
The MIB file has to be loaded first using the loadMibModule() of the MibOperations class. Then the getMibNode() is called to get the node associated with the MIB variable's object ID. This method can be called only when the name of the MIB module is not known. MibOperations mibops = new MibOperations(); try { mibops.loadMibModule("RFC1213-MIB"); } catch (Exception e) { System.out.println("Exception : "+e); System.exit(1); } MibNode node = mibops.getMibNode("sysDescr"); If the module name is known, the getMibNode() method of the MibModule class can be used to get the MIB node. When the getMibNode() method of the MibOperations class is called, the MIB node is searched in all the loaded MIB modules. Moreover, when a node occurs in more than one module, this method always returns the first occurrence of the node. For example, when getMibNode() method of MibOperations is called for the "rmon" node present in both RFC1271-MIB and RMON2-MIB, the MIB information corresponding to the first loaded module is returned. Therefore, to get a specific MIB node, it is advisable to use the getMibNode() method of the MibModule class. The MibNode class has methods to get all the details about a MIB variable. For example, the following code snippet gives some information about the selected MibNode. System.out.println("Syntax:"+node.getSyntax()); System.out.println("Access:"+node.printAccess()); System.out.println("Status:"+node.getStatus()); System.out.println("Reference:"+node.getReference()); System.out.println("OID:"+node.getNumberedOIDString()); System.out.println("Node:"+node.getOIDString()); System.out.println("Description:"+node.getDescription());
AdventNet, Inc.
64
The LeafSyntax class can be used to get the data type and value of the MibNode as shown below. LeafSyntax leafnode = node.getSyntax(); System.out.println("Value : "+leafnode.getType()); System.out.println("Data-type : "+leafnode.getEquivname());
AdventNet, Inc.
65
AdventNet, Inc.
66
Error parsing quoted filename Couldn't find file in search path specified
The various Parser Exceptions that you could get while using the MIBs API and the reasons for the same is tabulated below: Reason When the identifier starts with an uppercase letter, a special character, or a number, this The identifier should start with lowercase letter exception is thrown. The identifier, other than the Module Name and Textual-Convention, should start with a lower case letter. This exception is thrown when the identifiers The identifier Module Name or TextualModule Name and the Textual-Convention Convention should start with an uppercase letter. start with a lower case letter. The identifier should not start with number or If the identifier starts with a number or special character. special character, this exception is thrown. If the identifier for the MACRO construct (OBJECT-TYPE, OBJECT IDENTIFIER, The MACRO definition (OBJECT-TYPE,TRAPOBJECT-IDENTITY, TEXTUALTYPE, ...) may be missing. The identifier may be CONVENTION, MODULE-IDENTITY, invalid. NOTIFICATION-TYPE, NOTIFICATIONGROUP, OBJECT-GROUP, TRAP-TYPE, Error Message
AdventNet, Inc.
67
Reason AGENT-CAPABILITIES, MODULECOMPLIANCE, SEQUENCE) is missing, this exception is thrown. sysDescr DisplayString (SIZE (0..255)) ACCESS read-only STATUS mandatory DESCRIPTION " description ." ::= {system 1} Here the macro-type OBJECTTYPE is missing. Also, if the identifier contains special character or numbers, this exception is thrown. If the Identifier starts with an uppercase letter, exception 1 is thrown. 1. The identifier should not start with uppercase letter or For example, 2. In case of TEXTUALEgpNeighborLoss TRAP-TYPE If the assignment symbol ::= is missing, then CONVENTION/SEQUENCE construct the keyword ASSIGNMENT (::=) was missing exception 2 is thrown. For example, DisplayString OCTET STRING In the IMPORTS section, for example, IMPORTS mgmt, NetworkAddress, IpAddress 1. The imported item should be separated by the Counter, Gauge, TimeTicks symbol comma. FRM RFC1155-SMI 2. The IMPORTS construct should be terminated 1. Comma missing between the imported with the symbol semicolon. items IpAddress and Counter. 3. The keyword 'FROM' was missing. 2. Semicolon missing at the end of the IMPORTS construct. 3. The keyword FROM is mistyped. If the module name starts with a lower case letter, this exception is thrown. Module name should start with the uppercase letter. For example, rFC1213-MIB DEFINITIONS ::= BEGIN In the IMPORTS section, The name of the Imported item should be The imported item other than the TC, may 1. lowercase or start with an upper case. 2. uppercase, if TEXTUAL-CONVENTION The imported item may contain other than 3. SnmpConstruct or TypeName, which is the SnmpType or SnmpConstruct (all macros, name of an SNMP type or construct defined in such as OBJECT-TYPE, MODULEone of the SMI MIB modules; IDENTITY etc. and base datatypes such as INTEGER, COUNTER etc..). The OID component value should enclosed in This exception is thrown if the braces for the brackets or the OID construct may not end with OID construct is missing or the parenthesis right brace. for the name number OID is missing. For example, It may be expecting one of the following mgmt OBJECT IDENTIFIER ::= { internet } 1. The subOID may be missing. 1. Here the subOID 2 is missing. 2. The OID value reference should start with mgmt OBJECT IDENTIFIER ::= { Internet 2 lowercase letter. } 3. The OID value reference may start with 2. The OID value reference Internet starts modulename and separated with "." with an uppercase letter. Atleast one object should be present in this For example, construct, and In the OBJECT-GROUP construct, 1. The object should start with lowercase letter. OBJECTS { ifInOctets ifOutOctets,
Error Message
AdventNet, Inc.
68
Error Message 2. The object may start with Modulename which is separated with period (ModuleName.objectName). 3. The objects should be separated by comma.
Reason ifInUnknownProtos ,IfInErrors, ifOutErrors } 1. The object IfInErrors starts with an uppercase letter. 2. Comma missing between the object names ifInOctets and ifOutOctets. The Enterprise name should start with lowercase For example, letter or may start with module name which is ENTERPRISES Snmp separated with period. Here the Enterprise name starts with (ModuleName.enterprisesName) uppercase letter. If the INDEX or AUGMENTS keywords are The keyword 'INDEX' or 'AUGMENTS' was mistyped or missing in the Row Objects, this missing. exception is thrown. 1.The DEFVAL construct should enclosed in This exception is thrown when the braces braces. are missing in the DEFVAL field or the value 2. The default value within quotes. is not enclosed in quotes. This exception is thrown if there is an extra The additional comma present in comma at the end of the last SEQUENCE the SEQUENCE member. member. This exceptions is thrown if the value of the The quoted string was expected. Description and Reference fields is not enclosed in double quotes. For example, in the TRAP-TYPE, egpNeighborLoss TRAP-TYPE ENTERPRISE snmp VARIABLES { egpNeighAddr } The non-negative integer number was expected. DESCRIPTION "description" ::= -5 Here the trap number is negative. This exception is thrown if the value in the The default value is not correct DEFVAL field is not correct. This exception is thrown if the SYNTAX or The keyword 'SYNTAX' or 'SEQUENCE OF' is the SEQUENCE OF keyword is missing in missing. the OBJECT-TYPE construct. 1.The keyword 'ACCESS' or 'MAX-ACCESS' This exception is thrown if the keywords was missing. or 2. The keyword 'SEQUENCE OF' was missing. ACCESS, MAX-ACCESS or SEQUENCE OF or are missing in the OBJECT-TYPE construct. 3. The syntax with invalid subType construct. This exception is thrown if the OID value The invalid OID construct in the OBJECT-TYPE may not terminate with a right brace in the construct. OBJECT-TYPE construct. Was expecting the left brace or This exception is thrown if the brace (left or Was expecting the right brace. right) is missing. The keyword VARIABLES, DESCRIPTION, If one of the mentioned keywords are REFERENCE or the ASSIGNMENT (::=) may missing in the TRAP-TYPE construct, this be missing. exception is thrown. This exception is thrown if the keywords The keyword 'OBJECTS' or 'STATUS' may be OBJECTS and STATUS are missing in the missing. NOTIFICATION-TYPE construct. This exception is thrown if the REFERENCE The keyword 'REFERENCE' or 'ASSIGNMENT or ASSIGNMENT keyword is missing in the (::=)' may be missing. NOTIFICATION-TYPE construct. This exception is thrown if the REFERENCE The keyword 'REFERENCE' or 'MODULE' was or MODULE field is missing in the MODULEmissing COMPLIANCE construct.
AdventNet, Inc.
69
Error Message Was expecting MANDATORY-GROUPS or GROUP/OBJECT keyword One of the following keyword is missing. 1. In case of OBJECT construct SYNTAX , WRITE-SYNTAX, MIN-ACCESS or DESCRIPTION may be missing. 2. In case of GROUP construct keyword DESCRIPTION was missing. The keyword 'REVISION' was missing. One of these keyword 'REFERENCE' 'SUPPORTS', 'VARIATIONS' or ASSIGNMENT (::=) may be missing. One of these keyword 'SYNTAX', 'WRITESYNTAX', 'ACCESS', 'CREATION-REQUIRES' or 'DEFVAL' may be missing. The keyword 'DESCRIPTION' or 'REFERENCE' was missing. The 'ASSIGNMENT' or 'DEFVAL' keyword was missing. The ASSIGNMENT keyword was missing."
Reason This exception is thrown if the MANDATORY-GROUPS or GROUP/OBJECT keyword is missing in the MODULE-COMPLIANCE construct. This exception is thrown if the mentioned keywords are missing in the MODULECOMPLIANCE construct. This exception is thrown if the REVISION keyword is missing in the MODULEIDENTITY construct. This exception is thrown if the mentioned keywords are missing in the AGENTCAPABILITIES construct. This exception is thrown if the mentioned keywords are missing in the AGENTCAPABILITIES construct. This exception is thrown if the mentioned keywords are missing in the OBJECTTYPE construct. This exception is thrown if the mentioned keywords are missing in the OBJECTTYPE construct. This exception is thrown if the keyword "ASSIGNMENT" is missing. This exception is thrown if the keyword "keyword" is missing. The keywords are SEQUENCE, LAST-UPDATED, CONTACTINFO, DESCRIPTION, DESCRIPTION, ORGANIZATION, DISPLAY-HINT, STATUS, REFERENCE, SYNTAX, ENTERPRISES, VARIABLES, ASSIGNMENT (::=), OBJECTS, ACCESS, UNITS, MAXACCESS, MIN-ACCESS, DEFVAL, SEQUENCE OF, SEQUENCE or OBJECT IDENTIFIER, PRODUCTRELEASE,MODULE, MANDATORYGROUPS, SUPPORTS, INCLUDES, VARIATION, WRITE-SYNTAX, CREATION-REQUIRES, NOTIFICATIONS, and OBJECT IDENTIFIER. For example, ifTable OBJECT-TYPE SYNTAX SEQUENCE OF IfEntry ACCESS accessible STATUS mandatory DESCRIPTION "description" ::= { interfaces 2 } Here the ACCESS value is accessible, for the table node.
For the table and row OBJECT-TYPE construct the ACCESS value should be 'not-accessible'. or The access should contain one of these values : SMIv1/v2 access values. Here access is ACCESS/MAX-ACCESS for SMIv1 and SMIv2 respectively. SMIv1 access values: not-accessible","read-only","read-write","writeonly" SMIv2 access values: "not-accessible","read-only","read-write","writeonly","read-create" accessible-for-notify", notimplemented"
AdventNet, Inc.
70
Error Message
The 'INDEX' or 'AUGMENTS' keyword was missing in the table row object type construct which contains the sequence as {sequenceName}
Reason For example, ifEntry OBJECT-TYPE SYNTAX IfEntry ACCESS not-accessible STATUS mandatory DESCRIPTION "An interface entry containing objects at the subnetwork layer and below for a particular interface." ::= { ifTable 1 } This exception is thrown because here the field "INDEX { ifIndex } " is missing. The 'INDEX' or 'AUGMENTS' keyword was missing in the table row object type construct which contains the sequence as IfEntry. These nodes might not be defined in the MIB or in the imported MIB module and therefore the corresponding TC or nodeObject could not be resolved throwing this exception. For example, ifTable OBJECT-TYPE SYNTAX SEQUENCE OF IfEntry ACCESS not-accessible STATUS mandatory DESCRIPTION "description" ::= { interfaces 2 } ifEntry OBJECT-TYPE SYNTAX Iftry ACCESS not-accessible STATUS mandatory DESCRIPTION "description." INDEX { ifIndex } ::= { ifTable 1 } Ifntry ::= SEQUENCE { Here in the entry node ifEntry, the sequence name is mistyped as Iftry. This exception is thrown because there is no SEQUENCE by the name Iftry. Also the sequence name may not be the one that is defined in the syntax of ifTable. TCString1 ::= TCString2 TCString2 ::= TCString1 Here the TCString syntax is TCString2 whose syntax is TCString1. It gets into an indefinite loop throwing the CyclicTC exception. This exception is thrown if the module name starts with a lower case letter or contains a special character other than hyphen.
Was expecting a ModuleName and that should be in upper case or atleast in proper case
AdventNet, Inc.
71
Error Message
Reason For example, Integer32 ::= INTEGER Here Integer32 is being used as a label for defining the TC. This exception is thrown because Integer32 is a reserved word. If you do not wish to treat Integer32 as a reserved word, you have to use the method addLabel(String label) of the MibOperations class before loading the MIB. This exception is thrown if the subOID value exceeds the maximum value 4294967295.
AdventNet, Inc.
72
Database Schema
The following are the database tables that are used in AdventNet SNMP API for the MIB loading. Module Table (MODULETABLE) Module Identity Table (MODULEIDTYTABLE) Textual Convention Table (TCTABLE) Trap Table (TRAPTABLE) Unit Table (UNITTABLE) Node Table (NODETABLE) Object Type Table (OBJECTTYPETABLE) Dependancy Table (DEPENDANCYTABLE) Agent Capabilities and Module Compliance Table (ACMCTABLE) Module Compliance Modules Table (MCMTABLE) Agent Capabilities Modules Table (ACMTABLE) Agent Capabilities Variation Table (ACVTABLE) Sequence Table (SEQTABLE) Range List Table (RANGELISTTABLE) Object Group, Notification Group, Notification Type Table (OGNGNTTABLE)
Module Table contains the information about all the modules loaded in the database. For performance reasons, other tables are created for each MIB module. For example, for the MIB RFC1213-MIB, say MODULE1 is appended at the beginning of the table names, such as MODULE1MODULEIDTYTABLE, MODULE1TCTABLE, etc.
AdventNet, Inc.
73
AdventNet, Inc.
74
S. No 4 5 6 7
Description The Status field - Specifies the status of the definition. The Description field - Describes the node or item being defined. The Reference field - Specifies the source of the definition. The Default Value field - Specifies an acceptable value for a columnar object which may be used to create an instance of a row.
AdventNet, Inc.
75
7 8
DEFVALCREAOBJ DESCR
AdventNet, Inc.
76
The following macro definitions are defined only in SMIv2. MODULE-IDENTITY NOTIFICATION-TYPE OBJECT-IDENTITY OBJECT-GROUP AGENT-CAPABILITIES NOTIFICATION-GROUP MODULE-COMPLIANCE TEXTUAL-CONVENTION
OBJECT IDENTIFIER
Macro Definition lcName OBJECT IDENTIFIER ::= oidValue Example adventnet OBJECT IDENTIFIER ::= {enterprises 2162}
OBJECT-TYPE
Tables Macro Definition Examples ifTable OBJECT-TYPE SYNTAX SEQUENCE OF IfEntry MAX-ACCESS not-accessible STATUS current DESCRIPTION "Description" -- quoted string uses the NVT ASCII character set ::= {interfaces 2} ifTable OBJECT-TYPE SYNTAX SEQUENCE OF IfEntry MAX-ACCESS not-accessible STATUS current DESCRIPTION "Description" REFERENCE "reference" ::= {interfaces 2}
lcName OBJECT-TYPE SYNTAX SEQUENCE OF SequenceName MAX-ACCESS not-accessible STATUS StatusV2 DESCRIPTION Text [REFERENCE Text] ::= value (VALUE OBJECT IDENTIFIER)
AdventNet, Inc.
77
Row Objects Macro Definition lcName OBJECT-TYPE SYNTAX SequenceName MAX-ACCESS not-accessible STATUS StatusV2 DESCRIPTION Text [REFERENCE Text] Index ::= value (VALUE OBJECT IDENTIFIER) Index::= INDEX {[IMPLIED] nodeObjects [ , nodeObjects]*} | AUGMENTS {augments} -- * represents 0 or more occurrences Examples ifEntry OBJECT-TYPE SYNTAX IfEntry MAX-ACCESS not-accessible STATUS current DESCRIPTION "description" INDEX { ifIndex } ::= { ifTable 1 } ifXEntry OBJECT-TYPE SYNTAX IfXEntry MAX-ACCESS not-accessible STATUS current DESCRIPTION "description" AUGMENTS {ifEntry} ::= {ifXTable 1}
Columnar and Scalar Objects Macro Definition Examples ifSpeed OBJECT-TYPE SYNTAX Gauge32 MAX-ACCESS read-only STATUS current DESCRIPTION "description" ::= {ifEntry 5} etherStatsPkts OBJECT-TYPE SYNTAX Counter32 UNITS "Packets" MAX-ACCESS read-only STATUS current DESCRIPTION "description" ::= {etherStatsEntry 5} ifSpeed OBJECT-TYPE SYNTAX Gauge32 MAX-ACCESS read-only STATUS current DESCRIPTION "description" REFERENCE "reference" ::= {ifEntry 5}
lcName OBJECT-TYPE SYNTAX SyntaxV2 [UNITS Text] MAX-ACCESS AccessV2 STATUS StatusV2 DESCRIPTION Text [REFERENCE Text] [DEFVAL {DefvalV2}] ::= value (VALUE OBJECT IDENTIFIER)
TRAP-TYPE
Macro Definition Examples trapName TRAP-TYPE ENTERPRISE enterpriseName VARIABLES {variable1, variable2, variable3} DESCRIPTION "description" REFERENCE "reference" ::= 5
lcName TRAP-TYPE ENTERPRISE value [VARIABLES {Objects}] [DESCRIPTION Text] [REFERENCE Text] ::= value -- non-negative integer (range upto 2^32-1)
trapName TRAP-TYPE ENTERPRISE enterpriseName VARIABLES {variable1, variable2, variable3} Objects::= DESCRIPTION "description" objectName [ , objectName]* --objectName is the REFERENCE "reference" scalar or columnar object's name ::= 5 trapName TRAP-TYPE
AdventNet, Inc.
78
Macro Definition
Examples ENTERPRISE ModuleName.enterpriseName -the ModuleName where the enterpriseName was defined. VARIABLES {variable1, variable2, variable3} DESCRIPTION "description" REFERENCE "reference" ::= 5 trapName TRAP-TYPE ENTERPRISE enterpriseName ::= 5
MODULE-IDENTITY
Macro Definition Examples moduleIdty MODULE-IDENTITY LAST-UPDATED "9511090000Z" ORGANIZATION "organization" CONTACT-INFO "contact information" DESCRIPTION "description" REVISION "9304010000Z" DESCRIPTION "revision description" ::= { oid 1 } moduleIdty MODULE-IDENTITY LAST-UPDATED "9511090000Z" ORGANIZATION "organization" CONTACT-INFO "contact information DESCRIPTION "description" ::= { oid 2 }
lcName MODULE-IDENTITY LAST-UPDATED value(Update UTCTime) ORGANIZATION Text CONTACT-INFO Text DESCRIPTION Text [Revisions]* Revisions ::= REVISION value(Update UTCTime) DESCRIPTION Text
Note: UTC Time Format - YYMMDDHHMMZ where YY - last two digits of year MM - month (01 through 12) DD - day of month (01 through 31) HH - hours (00 through 23) MM - minutes (00 through 59) Z - denotes Greenwich Mean Time (GMT)
NOTIFICATION-TYPE
Macro Definition Examples notificationtype1 NOTIFICATION-TYPE OBJECTS {object1, object2, object3} STATUS current DESCRIPTION "Description" ::= {oid 1} notificationtype2 NOTIFICATION-TYPE STATUS current DESCRIPTION "Description" ::= {oid 2} notificationtype3 NOTIFICATION-TYPE OBJECTS {object1, object2, object3} STATUS current DESCRIPTION "Description" REFERENCE "reference" ::= {oid 3}
lcName NOTIFICATION-TYPE [OBJECTS {Objects}] STATUS StatusV2 DESCRIPTION Text [REFERENCE Text]
AdventNet, Inc.
79
OBJECT-IDENTITY
Macro Definition Examples objectIdty OBJECT-IDENTITY STATUS current DESCRIPTION "OID description" REFERENCE "reference" ::= {oid 3} objectIdty OBJECT-IDENTITY STATUS current DESCRIPTION "OID description" ::= {oid 4}
lcName OBJECT-IDENTITY STATUS StatusV2 DESCRIPTION Text [REFERENCE Text] ::=value(VALUE OBJECT IDENTIFIER)
OBJECT-GROUP
Macro Definition Examples objGroup1 OBJECT-GROUP OBJECTS {object1, object2, object3} STATUS current DESCRIPTION "Description" ::= {oid 1} objGroup2 OBJECT-GROUP OBJECTS {object1, object2, object3} STATUS current DESCRIPTION "Description" REFERENCE "reference" ::= {oid 2}
lcName OBJECT-GROUP OBJECTS {Objects} STATUS StatusV2 DESCRIPTION Text [REFERENCE Text] ::=value(VALUE OBJECT IDENTIFIER)
AGENT-CAPABILITIES
Macro Definition lcName AGENT-CAPABILITIES PRODUCT-RELEASE Text STATUS StatusV2 DESCRIPTION Text [REFERENCE Text] [Module]* ::=value(VALUE OBJECT IDENTIFIER) Module ::= SUPPORTS ModuleName INCLUDES {Groups} [Variations]* Variations ::= ObjectVariation | NotificationVariation NotificationVariation ::= VARIATION Objects [ACCESS AccessV2] DESCRIPTION Text ObjectVariation ::= VARIATION Objects [SYNTAX SyntaxV2] Examples agentcap1 AGENT-CAPABILITIES PRODUCT-RELEASE "Product-Release" STATUS current DESCRIPTION "Description" REFERENCE "REF" SUPPORTS RFC1213-MIB INCLUDES {groupObject1, groupObject2} VARIATION object1 SYNTAX IpAddress WRITE-SYNTAX INTEGER ACCESS read-only DEFVAL { 1 } DESCRIPTION "Variation Description" ::= {oid 1} agentcap2 AGENT-CAPABILITIES PRODUCT-RELEASE "Product-Release" STATUS current DESCRIPTION "Description" REFERENCE "REF" ::= {oid 2}
AdventNet, Inc.
80
Macro Definition [WRITE SYNTAX SyntaxV2] [ACCESS AccessV2] [CREATION-REQUIRES {Objects}] [DEFVAL {Defval}] DESCRIPTION Text Defval ::= Text | OID | nodeName | ModuleName.nodeName | ipAddress | binaryNumber | hexNumber | number
Examples agentcap3 AGENT-CAPABILITIES PRODUCT-RELEASE "Product-Release" STATUS current DESCRIPTION "Description" REFERENCE "REF" SUPPORTS RFC1213-MIB INCLUDES {groupObject1, groupObject2} ::= {oid 3}
NOTIFICATION-GROUP
Macro Definition Examples notificationgroup1 NOTIFICATION-GROUP NOTIFICATIONS {object1, object2} STATUS current DESCRIPTION "Description" ::= {oid 1} notificationgroup2 NOTIFICATION-GROUP NOTIFICATIONS {object1, object2} STATUS current DESCRIPTION "Description" REFERENCE "reference" ::= {oid 1}
lcName NOTIFICATION-GROUP NOTIFICATIONS {Objects} STATUS StatusV2 DESCRIPTION Text [REFERENCE Text] ::=value(VALUE OBJECT IDENTIFIER)
MODULE-COMPLIANCE
Macro Definition lcName MODULE-COMPLIANCE STATUS StatusV2 DESCRIPTION Text [REFERENCE Text] [Module]* ::=value(VALUE OBJECT IDENTIFIER) Module ::= MODULE ModuleName [MANDATORY-GROUPS {Objects }] [ComplianceGroup | Object] ComplianceGroup ::= GROUP {Objects} DESCRIPTION Text Object ::= OBJECT {Objects} [SYNTAX SyntaxV2] [WRITE-SYNTAX SyntaxV2] [MIN-ACCESS AccessV2] DESCRIPTION Text Examples modulecompliance1 MODULE-COMPLIANCE STATUS obsolete DESCRIPTION "Description" MODULE RFC1213-MIB MANDATORY-GROUPS {object1, object2} GROUP groupObject1 DESCRIPTION "Description" GROUP groupObject2 DESCRIPTION "Description" GROUP groupObject3 DESCRIPTION "Description" OBJECT object1 SYNTAX INTEGER MIN-ACCESS read-only DESCRIPTION "Description" OBJECT object2 SYNTAX INTEGER MIN-ACCESS read-only DESCRIPTION "Description" ::= {oid 1}
AdventNet, Inc.
81
TEXTUAL-CONVENTION
Macro Definition Examples TcName ::= TEXTUAL-CONVENTION DISPLAY-HINT "1x:" STATUS current DESCRIPTION "description" REFERENCE "reference" SYNTAX OCTET STRING TcName ::= TEXTUAL-CONVENTION STATUS current DESCRIPTION "description" SYNTAX OCTET STRING
ucName TEXTUAL-CONVENTION [DISPLAY-HINT Text] [STATUS StatusV2] DESCRIPTION Text [REFERENCE Text] SYNTAX SyntaxV2
AdventNet, Inc.
82
The above parameters are the common SNMPv2c parameters that need to be set while developing the applications and applets.
AdventNet, Inc.
83
SNMP Version
The three versions of SNMP that are in use are SNMPv1, SNMPv2c, and SNMPv3. If the SNMP version is not explicitly set, the default version is taken as SNMPv1. To set the specific SNMP version, we need to use the following methods listed in the table. The value 1 is for SNMPv2c. API Name Class/Component Name SnmpTarget SnmpRequestServer SnmpPoller SnmpTable API Methods Remarks Apart from this method, the static constants VERSION1, VERSION2c, and VERSION3 available in the bean can also be used to set the SNMP versions. This method sets the default version for the messages sent using this session. Both session and the PDU objects are created with a default version SNMPv1. This method sets the SNMP version - same as above - same as above -
HighLevel
setSnmpVersion(int)
LowLevel
setVersion(int)
Warning: When an application sends an SNMPv1 PDU using a session whose version is set to SNMP_VERSION_3, a SNMPv3 message is sent to the peer. This problem arises because the API uses SNMP_VERSION_1 as the default PDU version and it could not distinguish between applications leaving the version in PDU to default and setting it explicitly to SNMP_VERSION_1. To circumvent this problem, applications should set session version to SNMP_VERSION_1 and set the PDU version explicitly to SNMP_VERSION_2C or SNMP_VERSION_3 while communicating with v2c and v3 peers.
AdventNet, Inc.
84
SNMP Version
The three versions of SNMP that are in use are SNMPv1, SNMPv2c, and SNMPv3. Although SNMPv3 is yet to become an official standard, it is the widely deployed protocol. Applications should be able to handle all the versions of SNMP. If the SNMP version is not explicitly set, the default version is taken as SNMPv1. To set the specific SNMP version, we need to use the following methods listed in the table. The value 3 is for SNMPv3. API Name Class/Component Name API Methods Remarks
Apart from this method, the static SnmpTarget constants VERSION1, HighSnmpRequestServer setSnmpVersion(int) VERSION2c, and VERSION3 Level SnmpPoller available in the bean can also be SnmpTable used to set the SNMP versions. This method sets the default version for the messages sent SnmpSession Low-Level using this session. Both session setVersion(int) SnmpPDU and the PDU objects are created with a default version SNMPv1. This method sets the SNMP SnmpTarget RMI setSnmpVersion(int) version SnmpRequestServer SnmpTarget CORBA setSnmpVersion(int) - same as above SnmpRequestServer EJB SnmpTargetEJB setSnmpVersion(int) - same as above Note: While building SNMPv3 applications in the low-level API, SNMPv1, SNMPv2c, and SNMPv3 messages can be sent and received using the same session, irrespective of the version set in the session object. The version set in session is used to set the version for outgoing messages on the session, when it is not set in the message itself. For example, if a session version is set to SnmpAPI.SNMP_VERSION_3, and a PDU is sent without setting its version explicitly (the PDU has the default version of SnmpAPI.SNMP_VERSION_1), a SNMPv3 message is sent to the peer SNMP entity. On the other hand, if the PDU version is set explicitly to SnmpAPI.SNMP_VERSION_2C or SnmpAPI.SNMP_VERSION_3, the corresponding message will be sent to the peer entity. Warning: When an application sends an SNMPv1 PDU using a session whose version is set to SNMP_VERSION_3, a SNMPv3 message is sent to the peer. This problem arises because the API uses SNMP_VERSION_1 as the default PDU version and it could not distinguish between applications leaving the version in PDU to default and setting it explicitly to SNMP_VERSION_1. To circumvent this problem, applications should set session version to SNMP_VERSION_1 and set the PDU version explicitly to SNMP_VERSION_2C or SNMP_VERSION_3 while communicating with v2c and v3 peers.
AdventNet, Inc.
85
Host Name
In principle, there is no way to automatically discover the SNMP agent enabled nodes or devices. The management applications must be explicitly told where the agents reside. This can be the network address or the host name of the node in which the agent is installed. The management applications normally provide options to select the agent by entering the host name manually, selecting from a list of devices, or by clicking from a network topology map. Applications use the host name or the IP address of the device to communicate with the agent of the device. The following table lists the methods to be used for setting the host name parameters. API Name Class / Component Name SnmpTarget SnmpRequestServer SnmpPoller SnmpTable API Methods Remarks
HighLevel
LowLevel
RMI
CORBA EJB
Here the String can be either the hostname, including fully qualified setTargetHost(String) DNS hostname or IP address in string format, such as "192.168.1.4". The String can be hostname or IP address setRemoteAddress(InetAddress) in the string format. The UDPProtocolOptions setRemoteHost(String) InetAddress can be the IP address. The String can be either the hostname, including SnmpTarget fully qualified DNS setTargetHost(String) SnmpRequestServer hostname or IP address in string format. SnmpTarget - same as above setTargetHost(String) SnmpRequestServer - same as above SnmpTargetEJB setTargetHost(String)
Note: In the low-level API, the remoteHost attribute of SnmpPDU overrides the peername set in SnmpSession. This means, when remoteHost is null in SnmpPDU, messages are sent to the host, peername, set in the session. When remoteHost is not null in SnmpPDU, messages are sent to the remoteHost. It is a good practice to set the peername in SnmpSession to the host with which you intend to interact more frequently. Default peername is null, meaning when both peername in session and remoteHost in PDU are null, the exception "No remote IP address specified" is thrown.
AdventNet, Inc.
86
Port Number
The management applications communicate with the SNMP agents in the managed node in a particular port number. This remote port number is the UDP port 161. By default, all the SNMP request messages are received in this port. Sometimes, the agent may also be configured to receive messages in ports other than 161. The management applications normally have the provision to send request to the default port and also the option to set different port numbers. The following table lists the methods that need to be used for setting the Port Number rameters. API Name Class/Component Name SnmpTarget SnmpRequestServer SnmpPoller SnmpTable UDPProtocolOptions SnmpTarget SnmpRequestServer SnmpTarget SnmpRequestServer SnmpTargetEJB API Methods Remarks The default port number is "161". This method can be used to set the port number to other than 161.
High Level
setTargetPort(int)
Low Level
This method sets the remote port setRemotePort(int) on the peer to which the SNMP packets are sent. The default port number is "161". setTargetPort(int) This method can be used to set the port number to other than 161. setTargetPort(int) setTargetPort(int) - same as above - same as above -
Note: In the low-level API, the remotePort parameter in the SnmpPDU overrides the one in Snmpsession. It is a good practice to set remotePort in session to the port to which messages are often sent. When remotePort in SnmpPDU is 0, the message is sent to remotePort specified in the session.
AdventNet, Inc.
87
Community Name
SNMP mandates that the SNMP agents should accept request messages only if the community string in the message matches its community name. Therefore, the management application should always communicate with the agents along with the associated community name. The default SNMP community names are "public" for read-only (GET) operations and "private" for read-write (SET) operations. The management applications should have provision to include the community names in its request messages. Community strings are used to authenticate SNMP PDUs. Since SNMP packets are usually sent using UDP packets, there is no connection established as in the case of TCP/IP packets. Therefore, when a UDP packet arrives at the agent, the agent validates the packet. It accepts and sends a response if the community string of the PDU is equal to that set on the agent, else drops the packet. The agent does not change the community name after communicating. Applications typically communicate with the SNMP agents by specifying the community name of the agent. To set the community string, the following methods can be used. API Name Class/Component Name API Methods Remarks
HighLevel
The default community string is "public" and the default writeCommunity string is null. When writeCommunity is null, community itself is used for setCommunity(String) setWriteCommunity(String) SET operations. Therefore, applications should explicitly set the writeCommunity, before they can use it for SET operations. These methods set the setCommunity(String) read and write community setWriteCommunity(String) for outgoing requests. These methods set the setCommunity(String) setWriteCommunity(String) community name. setCommunity(String) - same as above setWriteCommunity(String) setCommunity(String) - same as above setWriteCommunity(String)
AdventNet, Inc.
88
Timeout and retries value are in secs. Timeout and retries value are in milliseconds. Timeout and retries value are in secs. - same as above - same as above -
Note: AdventNet SNMP API follows "exponential back off" algorithm to calculate the timeout and retry value. The timeout value specified increases exponentially with the retry value. In general, for the timeout value is 'T' and the retry value is 'R', the total time taken for the entire SNMP operation can be given as follows. r=R Total time taken =
r=0
T x 2^r
If the response is received in between, it is notified to the user either by returning the response PDU (in case of synchronous request) or by calling the callback method (in case of asynchronous request).
AdventNet, Inc.
89
Max Repetitions
A GETBULK request is performed by giving an OID along with two other parameters, namely a Max Repetitions value and a Non Repeaters value. The Max Repetitions value specifies the number of lexicographic successors to be returned for the remaining variables in the variable-bindings list. The default value is 50. The following table lists the methods that needs to be used for setting the Max Repetitions parameter. API Name High Level Class/Component Name SnmpTarget SnmpRequestServer SnmpPoller SnmpTable SnmpSession SnmpPDU SnmpTarget SnmpRequestServer SnmpTarget SnmpRequestServer SnmpTargetEJB API Methods setMaxRepetitions(int)
AdventNet, Inc.
90
Non Repeaters
A GETBULK request is performed by giving an OID along with two other parameters, namely a Max Repetitions value and a Non Repeaters value. The Non Repeaters value specifies the number of variables in the variable bindings list for which a single lexicographic successor is to be returned. The default value is 0. The following table lists the methods that needs to be used for setting the Non Repeaters value. API Name High Level Class/Component Name SnmpTarget SnmpRequestServer SnmpPoller SnmpTable SnmpSession SnmpPDU SnmpTarget SnmpRequestServer SnmpTarget SnmpRequestServer SnmpTarget API Methods setNonRepeaters(int)
AdventNet, Inc.
91
Trap Parameters
Management applications can receive trap messages sent by the agent. Following are the trap parameters that are to be set while developing applications.
Enterprise OID
This is the OID of the management enterprise that defines the trap message. The value is represented as an OBJECT IDENTIFIER and has a variable length. The following table displays the method that can be used for setting the enterprise OID. API Name Low Level Class/Component Name SnmpPDU API Methods setEnterpriseOID(SnmpOID)
Agent Address
This specifies the source IP address from which the trap was sent. The following table displays the method that can be used for setting the agent address. API Name Low Level Class/Component Name SnmpPDU API Methods setAgentAddr(String)
The generic traps are fixed and cannot be defined. On the other hand, it is possible to define multiple enterprise-specific traps. The trap message identity is determined based on the values contained in the Enterprises, Standard Trap Type, and Specific Trap Type fields of the Trap PDU. If the Trap Type value is zero through five, the trap is one of the generic traps and the value of the Specific Trap Type field will be zero. If the Trap type value is six, the trap is enterprise specific and is defined in a private MIB. It can take any integer value between 0 and 2147483647. The following table lists the methods that can be used for setting the trap type. The following table lists the methods that can be used for setting the generic and specific traps. API Name Low Level Class/Component Name API Methods Remarks
SnmpPDU
The setTrapType(int) method sets the generic type of the trap setTrapType(int) and the setSpecificType(String) setSpecificType(String) sets the specific type of the trap.
AdventNet, Inc.
92
Time Stamp
This is the value stored in the MIB-II sysUpTime variable converted into hours, minutes, and seconds. It is a 32-bit unsigned value indicating the number of centiseconds that have elapsed since the start of the SNMP agent and the sending of the trap. The following table displays the method that can be used for setting the time stamp. API Name Low Level Class/Component Name SnmpPDU API Methods setUpTime(long)
The traps are normally received in the UDP port no 162. However, this port number can be different and the applications should be able to handle this. In most operating systems, especially in Unix, port numbers 0 to 1023 are reserved. Only root users have permissions to use these ports. Therefore, if the SNMP port 162 is not available, it is preferable to choose the port numbers greater than 1023. The following table lists the methods that can be used for setting the trap port. API Name High Level Low Level RMI CORBA Class/Component Name SnmpTrapReceiver UDPProtocolOptions SnmpTrapReceiver SnmpTrapReceiver API Methods setPort(int) setPortWithExceptionMsg(int) setLocalPort(int) setPort(int) setPort(int)
An SNMPv2 trap may need to be translated to an SNMPv1 trap. The following table shows the notification parameters that make up an SNMPv1 trap and SNMPv2 traps. SNMPv1 Trap enterprise value agent address generic-trap value specific-trap value timestamp variable-bindings SNMPv2 Trap sysUpTime (first variable -binding) snmpTrapOID value (next variable bindings) snmpTrapEnterprise value (optional) additional variable bindings
AdventNet, Inc.
93
Handling Datatypes
Overview SMI Datayptes Textual Conventions
AdventNet SNMP API provides separate classes for the all the base data types, such as Integer, Counter, and so on. This section gives a detailed overview on the SMI datatypes. Moreover, AdventNet SNMP API supports the textual conventions MacAddress and DateAndTime, according to their definitions.
AdventNet, Inc.
94
Overview
AdventNet SNMP API provides separate classes for all the base data types, such as Integer, Counter, and so on. Moreover, the textual convention objects do not need separate classes because they are resolved into base data types. The textual convention objects are handled internally in the mibs package. AdventNet SNMP API supports the TAddress, MacAddress, and DateAndTime, according to their definitions. SNMP API supports the standard RFC's SMIv1 and SMIv2. The various data types for management information are given in the following table.
Data Types
SMIv1 Data Types INTEGER INTEGER (Enumerated) Gauge Counter TimeTicks OCTET STRING OBJECT IDENTIFIER IpAddress NetworkAddress Opaque SMIv2 Data Types Integer32 INTEGER (Enumerated) Unsigned32 Gauge32 Counter32 Counter64 TimeTicks OCTET STRING OBJECT IDENTIFIER IpAddress Opaque BITS
Specifies a list of labeled integer values. In SMIv1, the values should be greater than 0, whereas SMIv2 allows any values in the range (-2e31 to 2e31- 1) INTEGER (Enumerated) Example: Gauge INTEGER { true(1), false(2) }
Counter
Represents a non-negative integer, which holds at the maximum or minimum value specified in the range when the actual value goes over or below the range, respectively. Specifies a value which represents a count. The range is 0 to 4294967295.
AdventNet, Inc.
95
Description Specifies the elapsed time between two events, in units of hundredth of a second. The range is 0 to 2e32 - 1. Specifies octets of binary or textual information. While SMIv1 doesn't limit the number of octets, SMIv2 specifies a limit of 65535 octets. A size may be specified which can be fixed, varying, or of multiple ranges. Examples:
OCTET STRING
OCTET STRING -- length can vary from 0 to 65535 bytes OCTET STRING (SIZE(0..255)) OCTET STRING (SIZE(4)) -- fixed length of 4 bytes. OCTET STRING (SIZE(0 | 4 | 6)) -- varying with 0, 4, or 6 bytes
Identifies a type that has an assigned Object Identifier value Specifies an IPv4 address as a string of 4 octets. Allows a network address of any type to be specified. However, it is now obsolete. A value of this type is an IPv4 address. SMIv2 supports this type through the IpAddress type. Specifies octets of binary information. SMIv2 specifies a limit of 65535 octets while there is no limit in SMIv1. A size may be specified which can be fixed, varying, or of multiple ranges. A value of this type must be an encapsulation of ASN.1 BER encoded value. Examples: Opaque -- length can vary from 0 to 65535 bytes Opaque (SIZE(0..255)) Opaque (SIZE(4)) -- fixed length of 4 bytes. Opaque (SIZE(0 | 4 | 6)) -- varying with 0, 4, or 6 bytes
Opaque
Description Specifies a value whose range may include both positive and negative numbers. Range is 2e31 to 2e31 - 1 (SMIv1 doesn't specify minimum or maximum values for the range). Examples:
Integer32
Integer32(0..127) -- corresponds to an unsigned 8-bit integer Integer32 -- same as -- Integer32 (2147483648..2147483647) Integer32(0..40 | 50 | 65 | 90..100)
AdventNet, Inc.
96
Description Specifies a list of labeled integer values. In SMIv1 the values should be greater than 0, whereas SMIv2 allows any value in the range ( -2e31 to 2e31- 1).
INTEGER (Enumerated) Examples: INTEGER { true(1), false(2) } INTEGER { lessThan(-1), equal(0), greaterThan(1) }
Specifies a value whose range includes only non-negative integers (0 to 2e31 - 1). Examples: Unsigned32 Gauge32 Counter32 Unsigned32 -- same as Unsigned32(0..4294967295) Unsigned32(0..65535) -- corresponds to an unsigned 16 bit integer Unsigned32(0..10 | 50 | 65 | 90..100)
Counter64
TimeTicks
Represents a non-negative integer, which holds at the maximum or minimum value specified in the range when the actual value goes over or below the range, respectively. Specifies a value which represents a count. The range is 0 to 4294967295. Similar to Counter32, except that the range is now (0 to 2e64 -1). This type may only be used when a 32-bit counter rollover could occur in less than an hour. Otherwise, the Counter32 type must be used. It may only be used when backwards compatibility is not a requirement because this type is not available in SNMPv1. Specifies the elapsed time between two events, in units of hundredth of a second. Range is 0 to 2e32 - 1. Specifies octets of binary or textual information. While SMIv1 doesn't limit the number of octets, SMIv2 specifies a limit of 65535 octets. A size may be specified which can be fixed, varying, or of multiple ranges. Examples:
OCTET STRING
OCTET STRING -- length can vary from 0 to 65535 bytes. OCTET STRING (SIZE(0..255)) OCTET STRING (SIZE(4)) -- fixed length of 4 bytes. OCTET STRING (SIZE(0 | 4 | 6)) -- varying with 0, 4, or 6 bytes
Identifies a type that has an assigned Object Identifier value. Specifies an IPv4 address as a string of 4 octets. Specifies octets of binary information. SMIv2 specifies a limit of 65535 octets while there is no limit in SMIv1. A size may be specified which can be fixed, varying, or of multiple ranges. A value of this type must be an encapsulation of ASN.1 BER encoded value. Examples: Opaque -- length can vary from 0 to 65535 bytes. Opaque (SIZE(0..255))
Opaque
AdventNet, Inc.
97
Description Opaque (SIZE(4)) -- fixed length of 4 bytes. Opaque (SIZE(0 | 4 | 6)) -- varying with 0, 4, or 6 bytes
Specifies a collection of labeled bits. It provides a way to label individual bits in an octet (an extension of OCTET STRING type). BITS Example: BITS {0 (tcp), 1(netware), 2(netbios)}
The following table lists all the various syntax supported in our SNMP API and their equivalent data type in Java. S.No. 1 2 3 4 5 6 7 8 9 10 11 12 MIB Syntax INTEGER Integer32 Unsigned32 Gauge/Gauge32 Counter/Counter32 Counter64 TimeTicks OCTET STRING/BITS OBJECT IDENTIFIER NULL IpAddress Opaque Equivalent Data Type in Java Integer Integer Long Long Long long[2] Long byte[] int[] Null byte[4] byte[]
AdventNet, Inc.
98
SMI Datatypes
Integer32 Integer (Enumerated) Unsigned32 Gauge32 Counter32 Counter64 Timeticks OCTET STRING OBJECT IDENTIFIER IpAddress Opaque BITS
AdventNet SNMP API provides separate classes for all the SMI data types, such as INTEGER, OCTET STRING, and so on. Refer Setting Values for Datatypes to know the various values that are to be specified in a SET operation with respect to the SYNTAX of this object.
AdventNet, Inc.
99
Integer32
Integer32 specifies a value whose range may include both positive and negative numbers. Range is 2e31 to 2e31 - 1. Examples Integer32(0..127) -- corresponds to an unsigned 8-bit integer Integer32 -- same as -- Integer32 (-2147483648..2147483647) Integer32(0..40 | 50 | 65 | 90..100)
Create Variable
Using SnmpVar class The SnmpVar class is the base class for all SNMP variable classes. The createVariable(String value, byte type) method creates a new SnmpVar object with the specified type and value. String value = "2143483508"; SnmpVar snmpvar = SnmpVar.createVariable(value, SnmpAPI.INTEGER);
The string value should only be in decimal. Valid Usage SnmpVar snmpvar = SnmpVar.createVariable("123456", SnmpAPI.INTEGER); SnmpVar snmpvar = SnmpVar.createVariable("-12345", SnmpAPI.INTEGER); Invalid Usage SnmpVar snmpvar = SnmpVar.createVariable("test", SnmpAPI.INTEGER); The above usage is invalid because only decimal values are accepted and not any type of strings. SnmpVar snmpvar = SnmpVar.createVariable("0x12abcd", SnmpAPI.INTEGER); The above usage is invalid because only decimal values are accepted and not any hexadecimal values. SnmpVar snmpvar = SnmpVar.createVariable("12345678901234567", SnmpAPI.INTEGER); The above usage is invalid because the value exceeds the maximum limit of an integer. For all of the above invalid usages, an SnmpException is thrown. Using SnmpInt class The constructor of this class creates an SnmpInt object by taking integer value as argument.
AdventNet, Inc.
100
Using mibs package The following code snippet creates an SnmpVar object of Integer32 data type using the LeafSyntax class. String mibFile = "<mib name>"; String moduleName = "IF-MIB"; String nodeName = "ifMtu"; MibOperations mibOps = new MibOperations(); mibOps.loadMibModule(mibFile); MibModule module = mibOps.getMibModule(moduleName); SnmpOID snmpoid = mibOps.getSnmpOID(nodeName); MibNode node = module.getMibNode(snmpoid); LeafSyntax syntax = node.getSyntax(); String value = "2143483508"; SnmpVar snmpvar = syntax.createVariable(value); Valid Usage SnmpVar snmpvar = syntax.createVariable("65535");//decimal format SnmpVar snmpvar = syntax.createVariable("'1111111111111111'B");//binary format SnmpVar snmpvar = syntax.createVariable("'FFFF'h");//hex format Note: In the binary format, the value should be enclosed within single quotes and end with 'b or 'B. In the hex format, the value should be enclosed within single quotes and end with 'h or 'H.
1. The getVarObject() method returns the integer value as Integer object. int value = 12345; // 0x3039 SnmpInt snmpint = new SnmpInt(value); Integer obj = (Integer)snmpint.getVarObject(); 2. The toValue() method returns the integer value as Integer object. Integer obj = (Integer)snmpint.toValue(); 3. The toBytes() method returns the integer as a byte array of length 4. byte[] array = snmpint.toBytes(); This byte array contains the following values. array[0] = 0x00; array[1] = 0x00; array[2] = 0x30; array[3] = 0x39;
AdventNet, Inc.
101
4. The toString() method returns the integer value in decimal as a printable form. String value = snmpint.toString(); 5. The toTagString() method returns the integer value in decimal with tag 'INTEGER' attached to it. String tagstring = snmpint.toTagString(); This string contain the value "INTEGER: 12345". 6. The intValue() method returns the integer value as "int" int value = snmpint.intValue(); Using mibs package The toString() and toByteString() value of the variable as String. methods of the MibOperations class are used to retrieve the
The following commands retrieve the value of the created variable. String value = mibOps.toString(snmpvar, snmpoid); This string contains the value "2143483508". String value = mibOps.toString(snmpvarbind); This string contains the value "ifMtu:-->2143483508". String value = mibOps.toByteString(snmpvar, snmpoid); This string contains the value "2143483508". String value = mibOps.toByteString(snmpvarbind); This string contains the value "ifMtu:-->2143483508". String value = mibOps.toString(snmppdu); This string contains the following value. SNMP PDU (type unknown/unspecified) SNMP Version: Version 1 Remote Port: 0 Community: null Request ID: 0 Timeout: 0 Retries: 0 Error Status: no error SNMP PDU Variable Bindings: Object ID: .iso.org.dod.internet.mgmt.mib-2.interfaces.ifTable.ifEntry.ifMtu INTEGER: 2143483508 String value = mibOps.toByteString(snmppdu);
AdventNet, Inc.
102
This string contains the following value. SNMP PDU (type unknown/unspecified) SNMP Version: Version 1 Remote Port: 0 Community: null Request ID: 0 Timeout: 0 Retries: 0 Error Status: no error SNMP PDU Variable Bindings: Object ID: .iso.org.dod.internet.mgmt.mib-2.interfaces.ifTable.ifEntry.ifMtu INTEGER: 2143483508 String value = mibOps.toTagString(snmpvarbind); This string contains the following value. Object ID: .iso.org.dod.internet.mgmt.mib-2.interfaces.ifTable.ifEntry.ifMtu INTEGER: 2143483508 The value of an instance of an object with the syntax defined using this textual convention can be displayed using the DISPLAY-HINT clause. Refer Textual Conventions for more information on the DISPLAY-HINT clause. Note: In high-level API, these objects do not have separate classes because they are handled internally.
AdventNet, Inc.
103
INTEGER (Enumerated)
Enumerated integer specifies a list of labeled integer values. For example, INTEGER{min(1), max(32)} is an enumeration of integer. It should not be equated as range of numbers between 1 to 32. We cannot set number other than 1 and 32. If we try to set it will throw DataException. To set all numbers between 1 to 32, we must define the syntax as range of integer. The range of Integer should be defined as INTEGER(1..32), only then we can set value of 1 to 32. Example INTEGER {up(1), down(2), testing(3)}
Create Variable
Using SnmpVar class The SnmpVar class is the base class for all SNMP variable classes. The createVariable(String value, byte type) method creates a new SnmpVar object with the specified type and value. String value = "2143483508"; SnmpVar snmpvar = SnmpVar.createVariable(value, SnmpAPI.INTEGER) The string value should only be in decimal. Valid Usage SnmpVar snmpvar = SnmpVar.createVariable("123456", SnmpAPI.INTEGER); SnmpVar snmpvar = SnmpVar.createVariable("-12345", SnmpAPI.INTEGER); Invalid Usage SnmpVar snmpvar = SnmpVar.createVariable("test", SnmpAPI.INTEGER); The above usage is invalid because only decimal values are accepted and not any type of strings. SnmpVar snmpvar = SnmpVar.createVariable("0x12abcd", SnmpAPI.INTEGER); The above usage is invalid because only decimal values are accepted and not any hexadecimal values. SnmpVar snmpvar = SnmpVar.createVariable("12345678901234567", SnmpAPI.INTEGER); The above usage is invalid because the value exceeds the maximum limit of an integer. For all of the above invalid usages, an SnmpException is thrown. Using SnmpInt class The constructor of this class creates an SnmpInt object by taking integer value as argument.
AdventNet, Inc.
104
Using mibs package Let us now create an SnmpVar object of type enumerated integer using the LeafSyntax String mibFile = "<mib name>"; String moduleName = "RFC1213-MIB"; String nodeName = "ifOperStatus"; MibOperations mibOps = new MibOperations(); mibOps.loadMibModule(mibFile); MibModule module = mibOps.getMibModule(moduleName); SnmpOID snmpoid = mibOps.getSnmpOID(nodeName); MibNode node = module.getMibNode(snmpoid); LeafSyntax syntax = node.getSyntax(); String value = "up"; SnmpVar snmpvar = syntax.createVariable(value); Valid Usage SnmpVar snmpvar = syntax.createVariable("1"); SnmpVar snmpvar = syntax.createVariable("up"); class.
Note: Binary and hex values cannot be given for creating enumerated integers.
1. The getVarObject() method returns the integer value as Integer object. int value = 12345; // 0x3039 SnmpInt snmpint = new SnmpInt(value); Integer obj = (Integer)snmpint.getVarObject(); 2. The toValue() method returns the integer value as Integer object. Integer obj = (Integer)snmpint.toValue(); 3. The toBytes() method returns the integer as a byte array of length 4. byte[] array = snmpint.toBytes(); This byte array contains the following values. array[0] = 0x00; array[1] = 0x00; array[2] = 0x30; array[3] = 0x39; 4. The toString() method returns the integer value in decimal as a printable form. String value = snmpint.toString();
AdventNet, Inc.
105
5. The toTagString() method returns the integer value in decimal with tag 'INTEGER' attached to it. String tagstring = snmpint.toTagString(); This string contain the value "INTEGER: 12345". 6. The intValue() method returns the integer value as "int" int value = snmpint.intValue(); Using mibs package The toString() and toByteString() value of the variable as String. methods of the MibOperations class are used to retrieve the
The following commands retrieve the value of the created variable. String value = mibOps.toString(snmpvar, snmpoid); This string contains the value "up(1)". String value = mibOps.toString(snmpvarbind); This string contains the value "ifOperStatus:-->up(1)". String value = mibOps.toByteString(snmpvar, snmpoid); This string contains the value "up(1)". String value = mibOps.toByteString(snmpvarbind); This string contains the value "ifOperStatus:-->up(1)". String value = mibOps.toString(snmppdu); This string contains the following value. SNMP PDU (type unknown/unspecified) SNMP Version: Version 1 Remote Port: 0 Community: null Request ID: 0 Timeout: 0 Retries: 0 Error Status: no error SNMP PDU Variable Bindings: Object ID: .iso.org.dod.internet.mgmt.mib-2.interfaces.ifTable.ifEntry.ifOperStatus INTEGER: up(1) String value = mibOps.toByteString(snmppdu); This string contains the following value. SNMP PDU (type unknown/unspecified) SNMP Version: Version 1 Remote Port: 0 Community: null
AdventNet, Inc.
106
Request ID: 0 Timeout: 0 Retries: 0 Error Status: no error SNMP PDU Variable Bindings: Object ID: .iso.org.dod.internet.mgmt.mib-2.interfaces.ifTable.ifEntry.ifOperStatus INTEGER: up(1) String value = mibOps.toTagString(snmpvarbind); This string contains the following value. Object ID: .iso.org.dod.internet.mgmt.mib-2.interfaces.ifTable.ifEntry.ifOperStatus INTEGER: up(1) The getEnumlabels() gets the enumeration labels from LeafSyntax object. String[] labels = syntax.getEnumlabels(); for(int i =0; i< labels.length; i++) { System.out.println("enum labels: "+labels[i]); } The getEnumint() method is used to get the enumerated integers. int[] values = syntax.getEnumint(); for(int j =0; j< values.length; j++) { System.out.println("enum int: "+values[j]); } The getLabel() method of the LeafSyntax class gets the label corresponding to integer value. The getInt() method gets the integer value corresponding to label. Note: In high-level API, these objects do not have separate classes because they are handled internally.
AdventNet, Inc.
107
Unsigned32
Unsigned32 specifies a value whose range includes only non-negative integers (0 to 4294967295). Examples Unsigned32 -- same as Unsigned32(0..4294967295) Unsigned32(0..65535) -- corresponds to an unsigned 16 bit integer Unsigned32(0..10 | 50 | 65 | 90..100)
Create Variable
Using SnmpVar class The SnmpVar class is the base class for all SNMP variable classes. The createVariable(String value, byte type) method creates a new SnmpVar object with the specified type and value. String value = "4292967200"; SnmpVar snmpvar = SnmpVar.createVariable(value, SnmpAPI.UNSIGNED32) The string value should only be in decimal. Valid Usage SnmpVar snmpvar = SnmpVar.createVariable("4294967295", SnmpAPI.UNSIGNED32) // 0xffffffff SnmpVar snmpvar = SnmpVar.createVariable("0", SnmpAPI.UNSIGNED32) SnmpVar snmpvar = SnmpVar.createVariable("4294967296", SnmpAPI.UNSIGNED32) // 0x100000000 The above usage should be used carefully. The given value will be converted to zero while sending an SNMP request because only the least significant 4 bytes are taken. Invalid Usage SnmpVar snmpvar = SnmpVar.createVariable("test", SnmpAPI.UNSIGNED32); The above usage is invalid because only decimal values are accepted. SnmpVar snmpvar = SnmpVar.createVariable("429496729542949672954294967295", SnmpAPI.UNSIGNED32); The above usage is invalid because, the value given exceeds the maximum limit of the "long" value. SnmpVar snmpvar = SnmpVar.createVariable("0x123abc", SnmpAPI.UNSIGNED32); The above usage is invalid because only decimal values are accepted and not any hexadecimal values. For all of the above invalid usages, an SnmpException is thrown. Using SnmpUnsignedInt class The constructor of this class creates an SnmpUnsignedInt argument. object by taking a long type as
AdventNet, Inc.
108
long value = 4292967200; SnmpUnsignedInt snmpunsignedint = new SnmpUnsignedInt(value); Using mibs package The following code snippet creates an SnmpVar object of Unsigned32 data type using the LeafSyntax class. String mibFile = "<mib name>"; String moduleName = "<module name>"; String oid = "<OID>"; MibOperations mibOps = new MibOperations(); mibOps.loadMibModule(mibFile); MibModule module = mibOps.getMibModule(moduleName); SnmpOID snmpoid = mibOps.getSnmpOID(oid); MibNode node = module.getMibNode(snmpoid); LeafSyntax syntax = node.getSyntax(); String value = "4292967200"; SnmpVar snmpvar = syntax.createVariable(value); Valid Usage SnmpVar snmpvar = syntax.createVariable("65535"); SnmpVar snmpvar = syntax.createVariable("'1111111111111111'B"); SnmpVar snmpvar = syntax.createVariable("'FFFF'H"); Note: The value can be given in decimal, hex or binary format while sending an SNMP request because only the least significant 4 bytes are taken.
1. The getVarObject() returns the value as Long object. long value = 0xffffffffL; // the maximum value of an Unsigned32 SnmpUnsignedInt unsigned = new SnmpUnsignedInt(value); Long obj = (Long)unsigned.getVarObject(); 2. The toValue() method returns the value as Long object. Long obj = (Long )unsigned.toValue(); 3. The toBytes() method returns the integer as a byte array of length 4. byte[] array = unsigned.toBytes(); This byte array will contain the following values. array[0] = 0xff; array[1] = 0xff; array[2] = 0xff; array[3] = 0xff;
AdventNet, Inc.
109
4. The toString() method returns the integer value in decimal as a printable form. String value = unsigned.toString(); This string contains the value "4294967295". 5. The toTagString() method returns the integer value in decimal with the tag "UNSIGNED" attached to it. String tagstring = unsigned.toTagString(); This string contains the value "UNSIGNED: 4294967295". 6. The longValue() method returns the value as "long" long value = unsigned.longValue(); Using mibs package The toString() and toByteString() value of the variable as String. methods of the MibOperations class are used to retrieve the
String value = mibOps.toString(snmpvar, snmpoid); Note: In high-level API, these objects do not have separate classes because they are handled internally.
AdventNet, Inc.
110
Gauge32
Gauge32 represents a non-negative integer, which holds at the maximum or minimum value specified in the range when the actual value goes over or below the range, respectively.
Create Variable
Using SnmpVar class The SnmpVar class is the base class for all SNMP variable classes. The createVariable(String value, byte type) method creates a new SnmpVar object with the specified type and value. String value = "4200067295"; SnmpVar snmpvar = SnmpVar.createVariable(value, SnmpAPI.GAUGE); The string value should only be in decimal. Valid Usage SnmpVar snmpvar = SnmpAPI.GAUGE);// SnmpVar snmpvar = SnmpVar snmpvar = SnmpAPI.GAUGE);// SnmpVar.createVariable("4294967295", 0xffffffff SnmpVar.createVariable("0", SnmpAPI.GAUGE); SnmpVar.createVariable("4294967296", 0x100000000
The above usage should be used carefully. The given value will be converted to zero while sending an SNMP request because only the least significant 4 bytes are taken. Invalid Usage SnmpVar snmpvar = SnmpVar.createVariable("test", SnmpAPI.GAUGE); The above usage is invalid because only decimal values are accepted. SnmpVar snmpvar = SnmpVar.createVariable("429496729542949672954294967295", SnmpAPI.GAUGE); The above usage is invalid because, the value given exceeds the maximum limit of the "long" value. SnmpVar snmpvar = SnmpVar.createVariable("0x123abc", SnmpAPI.GAUGE); The above usage is invalid because only decimal values are accepted and not any hexadecimal values. For all of the above invalid usages, an SnmpException is thrown. Using SnmpGauge class The constructor of this class creates an SnmpGauge long value = 4200067295; SnmpGauge gauge= new SnmpGauge(value); object by taking a long type as argument.
AdventNet, Inc.
111
Using mibs package The following code snippet creates an SnmpVar object of Gauge32 data type using the LeafSyntax class. String mibFile = "<mib name>"; String moduleName = "IF-MIB"; String nodeName = "ifSpeed"; MibOperations mibOps = new MibOperations(); mibOps.loadMibModule(mibFile); MibModule module = mibOps.getMibModule(moduleName); SnmpOID snmpoid = mibOps.getSnmpOID(nodeName); MibNode node = module.getMibNode(snmpoid); LeafSyntax syntax = node.getSyntax(); String value = "4294967295"; SnmpVar snmpvar = syntax.createVariable(value); Valid Usage SnmpVar snmpvar = syntax.createVariable("65535"); SnmpVar snmpvar = syntax.createVariable("'1111111111111111'B"); SnmpVar snmpvar = syntax.createVariable("'FFFF'H"); Note: The value can be given in decimal, hex or binary format while sending an SNMP request because only the least significant 4 bytes are taken.
1. The getVarObject() returns the SnmpGauge value as Long object. long value = 0xffffffffL; // the maximum value of an Unsigned32 SnmpGauge gauge32 = new SnmpGauge(value); Long obj = (Long)gauge32.getVarObject(); 2. The toValue() method returns the SnmpGauge value as Long object. Long obj = (Long)gauge32.toValue(); 3. The toBytes() method returns the integer as a byte array of length 4. byte[] array = gauge32.toBytes(); This byte array will contain the following values. array[0] = 0xff; array[1] = 0xff; array[2] = 0xff; array[3] = 0xff; 4. The toString() method returns the integer value in decimal as a printable form. String value = gauge32.toString();
AdventNet, Inc.
112
This string contains the value "4294967295". 5. The toTagString() method returns the integer value in decimal with the tag "Gauge" attached to it. String tagstring = gauge32.toTagString(); This string contains the value "Gauge: 4294967295". 6. The longValue() method returns the SnmpGauge value as "long". long value = gauge32.longValue(); Using mibs package The toString() and toByteString() value of the variable as String. methods of the MibOperations class are used to retrieve the
The following commands retrieve the value of the created variable. String value = mibOps.toString(snmpvar, snmpoid); This string contains the value "4294967295". String value = mibOps.toString(snmpvarbind); This string contains the value "ifSpeed:-->4294967295". String value = mibOps.toByteString(snmpvar, snmpoid); This string contains the value "4294967295". String value = mibOps.toByteString(snmpvarbind); This string contains the value "ifSpeed:-->4294967295". String value = mibOps.toString(snmppdu); This string contains the following value. SNMP PDU (type unknown/unspecified) SNMP Version: Version 1 Remote Port: 0 Community: null Request ID: 0 Timeout: 0 Retries: 0 Error Status: no error SNMP PDU Variable Bindings: Object ID: .iso.org.dod.internet.mgmt.mib-2.interfaces.ifTable.ifEntry.ifSpeed GAUGE: 4294967295 String value = mibOps.toByteString(snmppdu);
AdventNet, Inc.
113
This string contains the following value. SNMP PDU (type unknown/unspecified) SNMP Version: Version 1 Remote Port: 0 Community: null Request ID: 0 Timeout: 0 Retries: 0 Error Status: no error SNMP PDU Variable Bindings: Object ID: .iso.org.dod.internet.mgmt.mib-2.interfaces.ifTable.ifEntry.ifSpeed GAUGE: 4294967295 String value = mibOps.toTagString(snmpvarbind); This string contains the following value. Object ID: .iso.org.dod.internet.mgmt.mib-2.interfaces.ifTable.ifEntry.ifSpeed GAUGE: 4294967295 Note: In high-level API, these objects do not have separate classes because they are handled internally.
AdventNet, Inc.
114
Counter32
Counter32 specifies a value which represents a count. The range is 0 to 4294967295.
Create Variable
Using SnmpVar class The SnmpVar class is the base class for all SNMP variable classes. The createVariable(String value, byte type) method creates a new SnmpVar object with the specified type and value. String value = "406744073709551600"; SnmpVar snmpvar = SnmpVar.createVariable(value, SnmpAPI.COUNTER) The string value should only be in decimal. Valid Usage SnmpVar snmpvar = SnmpVar.createVariable("4294967295", SnmpAPI.COUNTER);// 0xffffffff SnmpVar snmpvar = SnmpVar.createVariable("0", SnmpAPI.COUNTER); SnmpVar snmpvar = SnmpVar.createVariable("4294967296", SnmpAPI.COUNTER);// 0x100000000 The above usage should be used carefully. The given value will be converted to zero while sending an SNMP request because only the least significant 4 bytes are taken. Invalid Usage SnmpVar snmpvar = SnmpVar.createVariable("test", SnmpAPI.COUNTER); The above usage is invalid because only decimal values are accepted. SnmpVar snmpvar = SnmpVar.createVariable("429496729542949672954294967295", SnmpAPI.COUNTER); The above usage is invalid because, the value given exceeds the maximum limit of the "long" value. SnmpVar snmpvar = SnmpVar.createVariable("0x123abc", SnmpAPI.COUNTER); The above usage is invalid because only decimal values are accepted and not any hexadecimal values. For all of the above invalid usages, an SnmpException is thrown. Using SnmpCounter class The constructor of this class creates an SnmpCounter object by taking a long type as argument.
long value = 406744073709551600; SnmpCounter counter32 = new SnmpCounter(value); Using mibs package
AdventNet, Inc.
115
The following code snippet creates an SnmpVar object of Counter32 data type using the LeafSyntax class. String mibFile = "<mib name>"; String moduleName = "IF-MIB"; String nodeName = "ifInOctets"; MibOperations mibOps = new MibOperations(); mibOps.loadMibModule(mibFile); MibModule module = mibOps.getMibModule(moduleName); SnmpOID snmpoid = mibOps.getSnmpOID(nodeName); MibNode node = module.getMibNode(snmpoid); LeafSyntax syntax = node.getSyntax(); String value = "4294967295"; SnmpVar snmpvar = syntax.createVariable(value); Valid Usage SnmpVar snmpvar = syntax.createVariable("65535"); SnmpVar snmpvar = syntax.createVariable("'1111111111111111'B"); SnmpVar snmpvar = syntax.createVariable("'FFFF'H"); Note: The value can be given in decimal, hex or binary format while sending an SNMP request because only the least significant 4 bytes are taken.
1. The getVarObject() returns the SnmpCounter value as Long object. long value = 0xffffffffL; // the maximum value of an Unsigned32 SnmpCounter counter32 = new SnmpCounter(value); Long obj = (Long)counter32.getVarObject(); 2. The toValue() method returns the SnmpCounter value as Long object. Long obj = (Long)counter32.toValue(); 3. The toBytes() method returns the integer as a byte array of length 4. byte[] array = counter32.toBytes(); This byte array will contain the following values. array[0] = 0xff; array[1] = 0xff; array[2] = 0xff; array[3] = 0xff; 4. The toString() method returns the integer value in decimal as a printable form. String value = counter32.toString(); This string contains the value "4294967295".
AdventNet, Inc.
116
5. The toTagString() method returns the integer value in decimal with the tag "Counter" attached to it. String tagstring = counter32.toTagString(); This string contains the value "Counter: 4294967295". 6. The longValue() method returns the SnmpCounter value as an "long" long value = counter32.longValue(); Using mibs package The toString() and toByteString() value of the variable as String. methods of the MibOperations class are used to retrieve the
The following commands retrieve the value of the created variable. String value = mibOps.toString(snmpvar, snmpoid); This string contains the value "4294967295". String value = mibOps.toString(snmpvarbind); This string contains the value "ifInOctets:-->4294967295". String value = mibOps.toByteString(snmpvar, snmpoid); This string contains the value "4294967295". String value = mibOps.toByteString(snmpvarbind); This string contains the value "ifInOctets:-->4294967295". String value = mibOps.toString(snmppdu); This string contains the following value. SNMP PDU (type unknown/unspecified) SNMP Version: Version 1 Remote Port: 0 Community: null Request ID: 0 Timeout: 0 Retries: 0 Error Status: no error SNMP PDU Variable Bindings: Object ID: .iso.org.dod.internet.mgmt.mib-2.interfaces.ifTable.ifEntry.ifInOctets COUNTER: 4294967295 String value = mibOps.toByteString(snmppdu); This string contains the following value. SNMP PDU (type unknown/unspecified) SNMP Version: Version 1
AdventNet, Inc.
117
Remote Port: 0 Community: null Request ID: 0 Timeout: 0 Retries: 0 Error Status: no error SNMP PDU Variable Bindings: Object ID: .iso.org.dod.internet.mgmt.mib-2.interfaces.ifTable.ifEntry.ifInOctets COUNTER: 4294967295 String value = mibOps.toTagString(snmpvarbind); This string contains the following value. Object ID: .iso.org.dod.internet.mgmt.mib-2.interfaces.ifTable.ifEntry.ifInOctets COUNTER: 4294967295 Note: In high-level API, these objects do not have separate classes because they are handled internally.
AdventNet, Inc.
118
Counter64
Counter64 is similar to Counter32, except the range is now (0 to 18446744073709551615). This type may only be used when a 32-bit counter rollover could occur in less than an hour. It may be used only when backward compatibility is not a requirement because this type is not available in SNMPv1. The Counter64 value has 64 bits (unsigned long in Java). As Java does not support unsigned data type, Counter64 is stored as an array of two longs in the SnmpCounter64 object each containing 32bit value. Of the total 8 bytes of the Counter64 value, long[1] contains the high order 32 bit value of the Counter64 data and long[0] contains the low order 32 bit value. Therefore, if you need to construct Counter64 object using long array, you can split two long values with high and low 32 bits.
Create Variable
Using SnmpVar class The SnmpVar class is the base class for all SNMP variable classes. The createVariable(String value, byte type) method creates a new SnmpVar object with the specified type and value. String value = "16446740073709451310"; SnmpVar snmpvar = SnmpVar.createVariable(value, SnmpAPI.COUNTER64) The string value should only be in decimal. Valid Usage SnmpVar var = SnmpVar.createVariable("1", SnmpAPI.COUNTER64); SnmpVar var = SnmpVar.createVariable("18446744073709551615", SnmpAPI.COUNTER64); SnmpVar var = SnmpVar.createVariable("118446744073709551615", SnmpAPI.COUNTER64); The last value clearly exceeds the maximum of Counter64. The least significant 8 bytes are taken as the real value. Invalid Usage SnmpVar var = SnmpVar.createVariable("123ab3af", SnmpAPI.COUNTER64); The above usage is invalid because the value should be given only in decimal and not in hexadecimal. SnmpVar var = SnmpVar.createVariable("abdck", SnmpAPI.COUNTER64); The above usage is invalid because the value should be given as a decimal number and not as a string. Using SnmpCounter64 Class We can use the SnmpCounter64 constructor which takes BigInteger value as argument to construct the SnmpCounter64 object as follows. SnmpCounter64 counter = the value; long[] array = (long[])counter.getVarObject(); BigInteger big = new BigInteger(Long.toString(array[1], 16), 16); big = big.shiftLeft(32); big = big.or(new BigInteger(Long.toString(array[0], 16), 16));
AdventNet, Inc.
119
You can also get the BigInteger using the toBigInteger() method. The following table shows the values that are present in the long array. Value of SnmpCounter64 in Hex 0 aa aa aa aa aa aa bb aa aa aa aa bb bb aa aa aa aa ff ff ff ff ee ee ee ee Valid Usage java.math.BigInteger big = new java.math.BigInteger("1234567890"); SnmpCounter64 counter64 = new SnmpCounter64(big); java.math.BigInteger big = new java.math.BigInteger("1234567890"); byte[] array = big.toByteArray(); SnmpCounter64 counter64 = new SnmpCounter64(array); long[] array = { 0xffL , 0xffffffffL }; SnmpCounter64 counter64 = new SnmpCounter64(array); Invalid Usage long[] array = { 0x1f, 0xffL , 0xffffffffL }; SnmpCounter64 counter64 = new SnmpCounter64(array); In the above usage, the long array passed in should be of length 2. Using mibs package The following code snippet creates an SnmpVar object of Counter64 data type using the LeafSyntax class. String mibFile = "<mib name>"; String moduleName = "IF-MIB"; String nodeName = "ifHCInOctets"; MibOperations mibOps = new MibOperations(); mibOps.loadMibModule(mibFile); MibModule module = mibOps.getMibModule(moduleName); SnmpOID snmpoid = mibOps.getSnmpOID(nodeName); MibNode node = module.getMibNode(snmpoid); LeafSyntax syntax = node.getSyntax(); String value = "18446744073709551615"; SnmpVar snmpvar = syntax.createVariable(value); Valid Usage SnmpVar snmpvar = syntax.createVariable("'1111 1111 1111 1111 1111 1111 1111 1111 1111 1111 1111 1111 1111 1111 1111 1111'b"); SnmpVar snmpvar = syntax.createVariable("'FFFFFFFFFFFFFFFF'h"); Note: The value can be given in decimal, hex or binary format while sending an SNMP request because only the least significant 4 bytes are taken. Long[1] 0 0 0 bb bb bb ff ff ff Long[0] 0 aa aa aa aa aa aa aa aa aa aa aa aa aa aa ee ee ee ee
AdventNet, Inc.
120
1. The getVarObject() returns the SnmpCounter64 value as an long array of length 2. BigInteger big = new BigInteger("1234567890"); SnmpCounter64 counter64 = new SnmpCounter64(big); long[] longarray = (long[]) counter64.getVarObject(); This long array will be of length two and the long array[1] will contain the most significant 4 bytes and the longarray[0] will contain the least significant 4 bytes. longarray[1] = 0x00; longarray[1] = 0x499602d2; 2. The toValue() method returns the SnmpCounter64 value as an object of long array of length 2. long[] longarray = (long[]) counter64.getVarObject(); This long array will be of length two and the long array[1] will contain the most significant 4 bytes and the longarray[0] will contain the least significant 4 bytes. longarray[1] = 0x00; longarray[1] = 0x499602d2; 3. The toBytes() method returns the value as bytes. byte[] array = counter64.toBytes(); This byte array will contain the value split in the form of byte array of length 8. The byte array will contain the following bytes. array[0] = 0x00; array[1] = 0x00; array[2] = 0x00; array[3] = 0x00; array[4] = 0x49; array[5] = 0x96; array[6] = 0x02; array[7] = 0xD2; 4. The toString() method returns the value as a printable form. String str = counter64.toString(); This string will return the value 0x499602d2. 5. The toTagString() method returns the Counter64 value with the tag "COUNTER64" attached to it. String tagstring = snmpoid.toTagString(); This string contains the value "COUNTER64: 0x499602d2". 6. The longValue() method returns the SnmpCounter value as an "long" long value = counter32.longValue();
AdventNet, Inc.
121
Using mibs package The toString() and toByteString() value of the variable as String. methods of the MibOperations class are used to retrieve the
The following commands retrieve the value of the created variable. String value = mibOps.toString(snmpvar, snmpoid); This string contains the value "18446744073709551615". String value = mibOps.toString(snmpvarbind); This string contains the value "ifHCInOctets:-->18446744073709551615". String value = mibOps.toByteString(snmpvar, snmpoid); This string contains the value "18446744073709551615". String value = mibOps.toByteString(snmpvarbind); This string contains the value "ifHCInOctets:-->18446744073709551615". String value = mibOps.toString(snmppdu); This string contains the following value. SNMP PDU (type unknown/unspecified) SNMP Version: Version 1 Remote Port: 0 Community: null Request ID: 0 Timeout: 0 Retries: 0 Error Status: no error SNMP PDU Variable Bindings: Object ID: .iso.org.dod.internet.mgmt.mib-2.ifMIB.ifMIBObjects.ifXTable.ifXEntry.ifHCInOctets COUNTER64: 18446744073709551615 String value = mibOps.toByteString(snmppdu); This string contains the following value. SNMP PDU (type unknown/unspecified) SNMP Version: Version 1 Remote Port: 0 Community: null Request ID: 0 Timeout: 0 Retries: 0 Error Status: no error SNMP PDU Variable Bindings: Object ID: .iso.org.dod.internet.mgmt.mib-2.ifMIB.ifMIBObjects.ifXTable.ifXEntry.ifHCInOctets COUNTER64: 18446744073709551615
AdventNet, Inc.
122
String value = mibOps.toTagString(snmpvarbind); This string contains the following value. Object ID: .iso.org.dod.internet.mgmt.mib-2.ifMIB.ifMIBObjects.ifXTable.ifXEntry.ifHCInOctets COUNTER64: 18446744073709551615
AdventNet, Inc.
123
Timeticks
This represents a non-negative integer which specifies the elapsed time between two events, in units of hundredth of a second. The range is 0 to 2e32 - 1. When object types are defined in the MIB which use this ASN.1 type, the description of the object type identifies the reference period.
Create Variable
Using SnmpVar class The SnmpVar class is the base class for all SNMP variable classes. The createVariable(String value, byte type) method creates a new SnmpVar object with the specified type and value. SnmpVar snmpvar = SnmpVar.createVariable("4294967295", SnmpAPI.TIMETICKS) The string value should only be in decimal. Valid Usage SnmpVar snmpvar = SnmpVar.createVariable("4294967295", SnmpAPI.TIMETICKS) // 0xffffffff SnmpVar snmpvar = SnmpVar.createVariable("0", SnmpAPI.TIMETICKS) SnmpVar snmpvar = SnmpVar.createVariable("4294967296", SnmpAPI.TIMETICKS) // 0x100000000 Note: The above usage should be used carefully. The given value will be converted to zero while sending an SNMP request because only the least significant 4 bytes are taken. Invalid Usage SnmpVar snmpvar = SnmpVar.createVariable("test", SnmpAPI.TIMETICKS); The above usage is invalid because only decimal values are accepted. SnmpVar snmpvar = SnmpVar.createVariable("429496729542949672954294967295", SnmpAPI.TIMETICKS); The above usage is invalid because, the value given exceeds the maximum limit of the "long" value. SnmpVar snmpvar = SnmpVar.createVariable("0x123abc", SnmpAPI.TIMETICKS); The above usage is invalid because only decimal values are accepted and not any hexadecimal values. For all of the above invalid usages, an SnmpException is thrown. Using SnmpTimeticks class The constructor of this class creates an SnmpTimeticks object by taking a long type as argument.
AdventNet, Inc.
124
Using mibs package The following code snippet creates an SnmpVar object of Timeticks data type using the LeafSyntax class. String mibFile = "<mib name>"; String moduleName = "RFC1213-MIB"; String nodeName = "sysUpTime"; MibOperations mibOps = new MibOperations(); mibOps.loadMibModule(mibFile); MibModule module = mibOps.getMibModule(moduleName); SnmpOID snmpoid = mibOps.getSnmpOID(nodeName); MibNode node = module.getMibNode(snmpoid); LeafSyntax syntax = node.getSyntax(); String value = "4294967295"; SnmpVar snmpvar = syntax.createVariable(value);
long value = 0xffffffffL; // the maximum value of an Unsigned32 SnmpTimeticks timetick = new SnmpTimeticks(value); Long obj = (Long)timetick.getVarObject(); 2. The toValue() method returns the SnmpTimeticks value as Long object. Long obj = (Long )timetick.toValue(); 3. The toBytes() method returns the integer as a byte array of length 4. byte[] array = timetick.toBytes(); This byte array will contain the following values. array[0] = 0xff; array[1] = 0xff; array[2] = 0xff; array[3] = 0xff; 4. The toString() method returns the SnmpTimeticks value as a printable form. String value = timetick.toString(); This string contains the value in the form, "31 days, 1 hours, 39 minutes, 14 seconds". 5. The toTagString() method returns the integer value in decimal with the tag "Timeticks" attached to it. String tagstring = timetick.toTagString(); This string contains the value "Timeticks: 4294967295".
AdventNet, Inc.
125
6. The longValue() method returns the SnmpTimeticks value as "long". long value = timetick.longValue(); Using mibs package The toString() and toByteString() value of the variable as String. methods of the MibOperations class are used to retrieve the
The following commands retrieve the value of the created variable. String value = mibOps.toString(snmpvar, snmpoid); This string contains the value "497 days, 2 hours, 27 minutes, 52 seconds". String value = mibOps.toString(snmpvarbind); This string contains the value "sysUpTime:-->497 days, 2 hours, 27 minutes, 52 seconds". String value = mibOps.toByteString(snmpvar, snmpoid); This string contains the value "497 days, 2 hours, 27 minutes, 52 seconds". String value = mibOps.toByteString(snmpvarbind); This string contains the value "sysUpTime:-->497 days, 2 hours, 27 minutes, 52 seconds". String value = mibOps.toString(snmppdu); This string contains the following value. SNMP PDU (type unknown/unspecified) SNMP Version: Version 1 Remote Port: 0 Community: null Request ID: 0 Timeout: 0 Retries: 0 Error Status: no error SNMP PDU Variable Bindings: Object ID: .iso.org.dod.internet.mgmt.mib-2.system.sysUpTime TIMETICKS: 497 days, 2 hours, 27 minutes, 52 seconds. String value = mibOps.toByteString(snmppdu); This string contains the following value. SNMP PDU (type unknown/unspecified) SNMP Version: Version 1 Remote Port: 0 Community: null Request ID: 0 Timeout: 0 Retries: 0 Error Status: no error SNMP PDU Variable Bindings: Object ID: .iso.org.dod.internet.mgmt.mib-2.system.sysUpTime TIMETICKS: 497 days, 2 hours, 27 minutes, 52 seconds.
AdventNet, Inc.
126
String value = mibOps.toTagString(snmpvarbind); This string contains the following value. Object ID: .iso.org.dod.internet.mgmt.mib-2.system.sysUpTime TIMETICKS: 497 days, 2 hours, 27 minutes, 52 seconds. Note: In high-level API, these objects do not have separate classes because they are handled internally.
AdventNet, Inc.
127
OCTET STRING
OCTET STRING specifies octets of binary or textual information. While SMIv1 doesn't limit the number of octets, SMIv2 specifies a limit of 65535 octets. A size may be specified which can be fixed, varying, or of multiple ranges. Examples OCTET STRING -- length can vary from 0 to 65535 bytes OCTET STRING (SIZE(0..255)) OCTET STRING (SIZE(4)) -- fixed length of 4 bytes. OCTET STRING (SIZE(0 | 4 | 6)) -- varying with 0, 4, or 6 bytes
The OCTET STRING type is used to specify octets of binary or textual information. There is no limit to the maximum number of octets in a value of this type specified in SMI v1. For setting the value for a variable of type OCTET STRING, the type should be SnmpApi.STRING. If you want to set the value in hex format, the value should be within the single quotes and each octet should be separated by a colon(:). For setting value for variable of type MacAddress(octet string size(6)) you have to give value as colon separated string and should be enclosed within single quotes for example: "'12:13:14:15:16:17'".
Create Variable
Using SnmpVar class The SnmpVar class is the base class for all SNMP variable classes. The createVariable(String value, byte type) method creates a new SnmpVar object with the specified type and value. String value = "60000"; SnmpVar snmpvar = SnmpVar.createVariable(value, SnmpAPI.STRING); Any string can be given here. The string can also be given in ASCII and each byte should be specified in hexadecimal, separated by a colon and enclosed in single quotes. SnmpVar var = SnmpVar.createVariable("'10:ff:1a:b2'", SnmpAPI.STRING); Using SnmpString class The constructor of this class creates an SnmpString object by taking a string as argument.
String str = "testString"; SnmpString snmpstring = new SnmpString(str); The string can also be given in ASCII. Here each byte should be specified in hexadecimal, separated by a colon. This should be enclosed within single quotes. String str = "'10:ff:1a:b2'"; SnmpString snmpstring = new SnmpString(str); The SnmpString can be created using a specific character encoding using the following constructor. String str = "test"; String enc_string = "ISO8859_1"; SnmpString snmpstring = new SnmpString(str, enc_string);
AdventNet, Inc.
128
Using mibs package The following code snippet creates an SnmpVar object of OCTET STRING data type using the LeafSyntax class. String mibFile = "<mib name>"; String moduleName = "RMON-MIB"; String nodeName = "hostAddress"; MibOperations mibOps = new MibOperations(); mibOps.loadMibModule(mibFile); MibModule module = mibOps.getMibModule(moduleName); SnmpOID snmpoid = mibOps.getSnmpOID(nodeName); MibNode node = module.getMibNode(snmpoid); LeafSyntax syntax = node.getSyntax(); String value = "test"; // any string SnmpVar snmpvar = syntax.createVariable(value);
1. The getVarObject() returns the OCTET STRING value as String object. String str = "test"; SnmpString snmpstring = new SnmpString(str); String obj = (String)snmpstring.getVarObject(); 2. The toValue() method returns the OCTET STRING value as String object. String obj = (String )snmpstring.toValue(); 3. The toBytes() method returns the OCTET STRING value as a byte array. String obj = (String )snmpstring.toValue(); This byte array contains the following values. array[0] = 0x74; // ascii value of "t" array[1] = 0x65; // ascii value of "e" array[2] = 0x73; // ascii value of "s" array[3] = 0x74; // ascii value of "t" This string contains the value "74 65 73 74". These are the hexadecimal representation of each of the bytes. 4. The toString() method returns the OCTET STRING as a printable form. String value = snmpstring.toString(); This string contains the value "test". 5. The toTagString() method returns the OCTET STRING with the tag "STRING" attached to it. String tagstring = snmpstring.toTagString(); This string will contain the value "STRING: test".
AdventNet, Inc.
129
6. The toByteString() method returns a string with each of the bytes in the OCTET STRING in hexa decimal form. String bytestring = snmpstring.toByteString(); Using mibs package The toString() and toByteString() value of the variable as String. methods of the MibOperations class are used to retrieve the
The following commands retrieve the value of the created variable. String value = mibOps.toString(snmpvar, snmpoid); This string contains the value "test". String value = mibOps.toString(snmpvarbind); This string contains the value "hostAddress:-->test". String value = mibOps.toByteString(snmpvar, snmpoid); This string contains the value "74 65 73 74". String value = mibOps.toByteString(snmpvarbind); This string contains the value "hostAddress:-->74 65 73 74". String value = mibOps.toString(snmppdu); This string contains the following value. SNMP PDU (type unknown/unspecified) SNMP Version: Version 1 Remote Port: 0 Community: null Request ID: 0 Timeout: 0 Retries: 0 Error Status: no error SNMP PDU Variable Bindings: Object ID: .iso.org.dod.internet.mgmt.mib-2.rmon.hosts.hostTable.hostEntry.hostAddress STRING: test String value = mibOps.toByteString(snmppdu); This string contains the following value. SNMP PDU (type unknown/unspecified) SNMP Version: Version 1 Remote Port: 0 Community: null Request ID: 0 Timeout: 0 Retries: 0 Error Status: no error
AdventNet, Inc.
130
SNMP PDU Variable Bindings: Object ID: .iso.org.dod.internet.mgmt.mib-2.rmon.hosts.hostTable.hostEntry.hostAddress STRING: 74 65 73 74 String value = mibOps.toTagString(snmpvarbind); This string contains the following value. Object ID: .iso.org.dod.internet.mgmt.mib-2.rmon.hosts.hostTable.hostEntry.hostAddress STRING: test DISPLAY-HINT The value of an instance of an object with the syntax defined using this textual convention can be displayed using the DISPLAY-HINT clause. Refer Textual Conventions for more information. Note: In high-level API, these objects do not have separate classes because they are handled internally.
AdventNet, Inc.
131
OBJECT IDENTIFIER
OBJECT IDENTIFIER identifies a type that has an assigned Object Identifier value.
Create Variable
Using SnmpVar class The SnmpVar class is the base class for all SNMP variable classes. The createVariable(String value, byte type) method creates a new SnmpVar object with the specified type and value. If the OID does not start with a dot, the string ".1.3.6.1.2.1." is prefixed to the OID. String value = ".1.3.6.1.2.1.1.2"; SnmpVar snmpvar= SnmpVar.createVariable(value, SnmpAPI.OBJID); Valid Usage SnmpVar var = SnmpVar.createVariable("1.1.0", SnmpAPI.OBJID); SnmpVar var = SnmpVar.createVariable(".1.3.6.1.2.1.1.5.0", SnmpAPI.OBJID); The above usage should be used carefully. The given value will be converted to zero while sending an SNMP request because only the least significant 4 bytes are taken. Invalid Usage SnmpVar var = SnmpVar.createVariable("sysDescr", SnmpAPI.OBJID); /td> The above usage is invalid because, the string argument will accept OIDs only in dotted form and not as a string. SnmpVar var = SnmpVar.createVariable(".1.3.6.1.2.1.abcd", SnmpAPI.OBJID); The above usage is invalid because, each of the sub-identifier should be an integer in decimal form. SnmpVar var = SnmpVar.createVariable(".1a.b3.6d.ff.1.2.a", SnmpAPI.OBJID); The above usage is invalid because, each of the sub-identifier should be an integer in decimal form and not in hexa decimal form. Using SnmpOID class The constructor of this class creates an SnmpOID object by taking String as argument.
String value = ".1.3.6.1.2.1.1.2"; SnmpOID snmpoid = new SnmpOID(value); The following command also creates an SnmpOID object. int[] oids = {1, 3, 6, 1, 2, 1, 1, 1, 0}; SnmpOID oid = new SnmpOID(oids);
AdventNet, Inc.
132
Using mibs package The following code snippet creates an SnmpVar object of OBJECT IDENTIFIER data type using the LeafSyntax class. String mibFile = "<mib name>"; String moduleName = "<RFC1213-MIB>"; String nodeName = "sysObjectID"; MibOperations mibOps = new MibOperations(); mibOps.loadMibModule(mibFile); MibModule module = mibOps.getMibModule(moduleName); SnmpOID snmpoid = mibOps.getSnmpOID(nodeName); MibNode node = module.getMibNode(snmpoid); LeafSyntax syntax = node.getSyntax(); String value = ".1.3.6.1.2.1.1.1.0"; //valid numbered OID SnmpVar snmpvar = syntax.createVariable(value); Valid Usage SnmpVar snmpvar = syntax.createVariable(".1.3.6.1.2.1.1.1.0"); SnmpVar snmpvar = syntax.createVariable("1.1.0"); Note: If the OID does not start with a dot, the string ".1.3.6.1.2.1." is prefixed to the OID.
1. The getVarObject() returns the OBJECT IDENTIFIER value as Long object. String str = ".1.3.6.1.2.1.1.1.0"; SnmpOID oid = new SnmpOID(str); String obj = (String)snmpoid.getVarObject(); This string contains the value ".1.3.6.1.2.1.1.1.0". 2. The toValue() method returns the OBJECT IDENTIFIER value as an array of ints. int[] obj = (int[])snmpoid.toValue(); This integer array contains the following values in the given order. obj[0] = 1; obj[1] = 3; obj[2] = 6; obj[3] = 1; obj[4] = 2; obj[5] = 1; obj[6] = 1; obj[7] = 1; obj[8] = 0;
AdventNet, Inc.
133
3. The toBytes() method returns the OBJECT IDENTIFIER as a byte array. byte[] array = snmpoid.toBytes(); This byte array will contain the following values. array[0] = 0x00; array[1] = 0x00; array[2] = 0x00; array[3] = 0x01; array[4] = 0x00; array[5] = 0x00; array[6] = 0x00; array[7] = 0x03; array[8] = 0x00; array[9] = 0x00; array[10] = 0x00; array[11] = 0x06; array[12] = 0x00; array[13] = 0x00; array[14] = 0x00; array[15] = 0x01; array[16] = 0x00; array[17] = 0x00; array[18] = 0x00; array[19] = 0x02; array[20] = 0x00; array[21] = 0x00; array[22] = 0x00; array[23] = 0x01; array[24] = 0x00; array[25] = 0x00; array[26] = 0x00; array[27] = 0x01; array[28] = 0x00; array[29] = 0x00; array[30] = 0x00; array[31] = 0x01; array[32] = 0x00; array[33] = 0x00; array[34] = 0x00; array[35] = 0x00; Here each of the value in the integer array will be converted into an array of 4 bytes. 4. The toString() method returns the OBJECT IDENTIFIER value as a printable form. String value = snmpoid.toString(); This string will contain the value ".1.3.6.1.2.1.1.1.0". 5. The toTagString() method returns the integer value in decimal with the tag "Object ID" attached to it. String tagstring = snmpoid.toTagString(); This string will contain the value "Object ID: .1.3.6.1.2.1.1.1.0". Using mibs package The toString() and toByteString() value of the variable as String. methods of the MibOperations class are used to retrieve the
The following commands retrieve the value of the created variable. String value = mibOps.toString(snmpvar, snmpoid); This string contains the value ".iso.org.dod.internet.mgmt.mib-2.system.sysDescr.0". String value = mibOps.toString(snmpvarbind); This string contains the value "sysObjectID:-->.iso.org.dod.internet.mgmt.mib-2.system.sysDescr.0". String value = mibOps.toByteString(snmpvar, snmpoid); This string contains the value ".iso.org.dod.internet.mgmt.mib-2.system.sysDescr.0". String value = mibOps.toByteString(snmpvarbind); This string contains the value "sysObjectID:-->.iso.org.dod.internet.mgmt.mib-2.system.sysDescr.0". String value = mibOps.toString(snmppdu);
AdventNet, Inc.
134
This string contains the following value. SNMP PDU (type unknown/unspecified) SNMP Version: Version 1 Remote Port: 0 Community: null Request ID: 0 Timeout: 0 Retries: 0 Error Status: no error SNMP PDU Variable Bindings: Object ID: .iso.org.dod.internet.mgmt.mib-2.system.sysObjectID OBJID: .iso.org.dod.internet.mgmt.mib-2.system.sysDescr.0 String value = mibOps.toByteString(snmppdu); This string contains the following value. SNMP PDU (type unknown/unspecified) SNMP Version: Version 1 Remote Port: 0 Community: null Request ID: 0 Timeout: 0 Retries: 0 Error Status: no error SNMP PDU Variable Bindings: Object ID: .iso.org.dod.internet.mgmt.mib-2.system.sysObjectID OBJID: .iso.org.dod.internet.mgmt.mib-2.system.sysDescr.0 String value = mibOps.toTagString(snmpvarbind); This string contains the following value. Object ID: .iso.org.dod.internet.mgmt.mib-2.system.sysObjectID OBJID: .iso.org.dod.internet.mgmt.mib-2.system.sysDescr.0 Note: In high-level API, these objects do not have separate classes because they are handled internally.
AdventNet, Inc.
135
IpAddress
IpAddress is the string of four octets. A value of IpAddress type is an IPv4 address. A value is encoded as four bytes in network byte order.
Create Variable
Using SnmpVar class The SnmpVar class is the base class for all SNMP variable classes. The createVariable(String value, byte type) method creates a new SnmpVar object with the specified type and value. String value = "192.168.5.99"; SnmpVar snmpvar = SnmpVar.createVariable(value, SnmpAPI.IPADDRESS) Valid Usage SnmpVar var = SnmpVar.createVariable("192.168.1.137", SnmpAPI.IPADDRESS); SnmpVar var = SnmpVar.createVariable("localhost", SnmpAPI.IPADDRESS); The above should be used only in case of applications and not in applets, because the above call will do a DNS lookup and hence this is not possible in applets. Invalid Usage SnmpVar var = SnmpVar.createVariable("someUnknownHost", SnmpAPI.IPADDRESS); SnmpVar var = SnmpVar.createVariable("1.2.3.4.5.6", SnmpAPI.IPADDRESS);//invalid OID Using SnmpIpAddress class The constructor of this class creates an SnmpIpAddress object by String as argument.
String value = "192.168.5.99"; SnmpIpAddress ipadd = new SnmpIpAddress(value); The following command also creates an SnmpIpAddress object. byte[] values = {(byte)192, (byte)168, (byte)5, (byte)99}; SnmpIpAddressipadd = new SnmpIpAddress(values); Valid Usage String str = "192.168.1.137"; SnmpIpAddress snmpipaddress = new SnmpIpAddress(str); String str = "localhost"; SnmpIpAddress snmpipaddress = new SnmpIpAddress(str); byte[] array = { 1, 2, 3, 4 }; // represents 1.2.3.4 SnmpIpAddress snmpipaddress = new SnmpIpAddress(array); byte[] array = { -64, -88, 1, -119 }; // represents 192.168.1.137 SnmpIpAddress snmpipaddress = new SnmpIpAddress(array)
AdventNet, Inc.
136
Invalid Usage String str = "1.2.3.4.5.6"; SnmpIpAddress addr = new SnmpIpAddress(str); String str = "someUnknownHost"; SnmpIpAddress snmpipaddress = new SnmpIpAddress(str); For the above usages, the IP address in that message is sent as null. That is, an IP address of length zero is sent. byte[] array = { 1, 2, 3 }; SnmpIpAddress snmpipaddress = new SnmpIpAddress(array); byte[] array = { 1, 2, 3, 4, 5 }; SnmpIpAddress snmpipaddress = new SnmpIpAddress(array); byte[] array = null; SnmpIpAddress snmpipaddress = new SnmpIpAddress(array); For the above three usages, the IP address is sent as 0.0.0.0. Using mibs package The following code snippet creates an SnmpVar object of SnmpIpAddress data type using the LeafSyntax class. String mibFile = "<mib name>"; String moduleName = "RFC1213-MIB"; String nodeName = " udpLocalAddress"; MibOperations mibOps = new MibOperations(); mibOps.loadMibModule(mibFile); MibModule module = mibOps.getMibModule(moduleName); SnmpOID snmpoid = mibOps.getSnmpOID(nodeName); MibNode node = module.getMibNode(snmpoid); LeafSyntax syntax = node.getSyntax(); String value = "192.168.5.99"; //valid IP address SnmpVar snmpvar= syntax.createVariable(value); Valid Usage SnmpVar snmpvar= syntax.createVariable("192.168.1.100");//dotted IP address SnmpVar snmpvar = syntax.createVariable("<hostName>");//valid host name SnmpVar snmpvar = syntax.createVariable("'C0A80164'H");//hex format SnmpVar snmpvar = syntax.createVariable("'11000000101010000000000101100100'B");//bina ry format
Note: The input can be given in the hex and binary format. The value should contain four bytes. UnknownHostException is thrown if the host name or the IpAddress is invalid.
AdventNet, Inc.
137
1. The getVarObject() returns the SnmpIpAddress value as String object. String str = "192.168.1.137"; SnmpIpAddress snmpipaddress = new SnmpIpAddress(str); String str = (String)snmpipaddress.getVarObject(); The above string contains the value "192.168.1.137". 2. The toValue() method returns the SnmpIpAddress value as String object. String str = (String)snmpipaddress.toValue(); The above string contains the value "192.168.1.137". 3. The toBytes() method returns as a byte array. byte[] array = snmpipaddress.toBytes(); The above byte array contains the following values. array[0] = 0xc0; // 192 in decimal array[1] = 0xa8; // 168 in decimal array[2] = 0x01; // 1 in decimal array[3] = 0x89; // 137 in decimal 4. The toString() method returns the value as a printable form. String str = snmpipaddress.toString(); The above string contains the value "192.168.1.137". 5. The toTagString() method returns the value with the tag "IpAddress" attached to it. String str = snmpipaddress.toTagString(); The above string contains the value "IpAddress: 192.168.1.137". Using mibs package The toString() and toByteString() value of the variable as String. methods of the MibOperations class are used to retrieve the
The following commands retrieve the value of the created variable. String value = mibOps.toString(snmpvar, snmpoid); This string contains the value "192.168.5.99". String value = mibOps.toString(snmpvarbind);
AdventNet, Inc.
138
This string contains the value "udpLocalAddress:-->192.168.5.99". String value = mibOps.toByteString(snmpvar, snmpoid); This string contains the value "192.168.5.99". String value = mibOps.toByteString(snmpvarbind); This string contains the value "udpLocalAddress:-->192.168.5.99". String value = mibOps.toString(snmppdu); This string contains the following value. SNMP PDU (type unknown/unspecified) SNMP Version: Version 1 Remote Port: 0 Community: null Request ID: 0 Timeout: 0 Retries: 0 Error Status: no error SNMP PDU Variable Bindings: Object ID: .iso.org.dod.internet.mgmt.mib-2.udp.udpTable.udpEntry.udpLocalAddress IPADDRESS: 192.168.5.99 String value = mibOps.toByteString(snmppdu); This string contains the following value. SNMP PDU (type unknown/unspecified) SNMP Version: Version 1 Remote Port: 0 Community: null Request ID: 0 Timeout: 0 Retries: 0 Error Status: no error SNMP PDU Variable Bindings: Object ID: .iso.org.dod.internet.mgmt.mib-2.udp.udpTable.udpEntry.udpLocalAddress IPADDRESS: 192.168.5.99 String value = mibOps.toTagString(snmpvarbind); This string contains the following value. Object ID: .iso.org.dod.internet.mgmt.mib-2.udp.udpTable.udpEntry.udpLocalAddress IPADDRESS: 192.168.5.99 Note: In high-level API, these objects do not have separate classes because they are handled internally.
AdventNet, Inc.
139
Opaque
Opaque specifies octets of binary information. SMIv2 specifies a limit of 65535 octets while there is no limit in SMIv1. A size may be specified which can be fixed, varying, or of multiple ranges. A value of this type must be an encapsulation of ASN.1 BER encoded value. The Opaque type is provided solely for backward-compatibility, and shall not be used for newlydefined object types. This type supports the capability to pass arbitrary ASN.1 syntax. A value is encoded using the ASN.1 Basic Encoding Rules [4] into a string of octets. This, in turn, is encoded as an OCTET STRING, in effect "double-wrapping" the original ASN.1 value. Note that a conforming implementation need only be able to accept and recognize opaquely-encoded data. It need not be able to unwrap the data and then interpret its contents. A requirement on "standard" MIB modules is that no object may have a SYNTAX clause value of Opaque. Hence this data type should not be used for newly-defined object types. Note: In high-level API, these objects do not have separate classes because they are handled internally.
AdventNet, Inc.
140
BITS
BITS is a pseudo data type that specifies a collection of labelled bits. It provides a way to label individual bits in an octet (an extension of OCTET STRING type). BITS is numbered by its position starting at zero an must be contiguously numbered till the last bit. Position zero is the high order bit of the first octet of the string. Position 7 is the low order bit in the second octet of the string. Position 8 is the high order bit in the second octet of string and so on. When the number of bits is not a multiple of eight, the remaining bits will be in the final octet. If the number of bits is 11, the first eight bits will be in the first octet and the next 3 bits will be in the second (final) octet. The remaining five bits in the final octet will be set to zero by default. The value of the BITS datatype can be either hexadecimal or binary. Hexadecimal values end with 'h'/'H'and binary values end with 'b'/ 'B'. Example Consider the syntax for BITS as follows. BITS {sunday(0), monday(1), tuesday(2), wednesday(3), thursday(4), friday(5), saturday(6)} If we want to set the value for monday, tuesday, and friday, the value can be set in any of the following format. {sunday(0), monday(1), tuesday(2), wednesday(3), thursday(4), friday(5), saturday(6)} 0 1 1 0 0 1 0 In binary format, any of the following values can be set. '01100100'b '01100100'B 01100100b 01100100B 011001b 011001B In hex format, the following values can be set. '64'h '64'H 64H 64h In binary format, we append the zeros to get the minimum of 8 bits. For example, if the value is '80'h, you can give it as '8'h or '1'b. We append the zeros to get the multiple of 8 bits. Therefore, it becomes '80'h or '10000000'b. In both cases, note that the last character is 'b' or 'h'. We can also set the value by giving the BITS label which is separated by a comma or a space. And the value can be a combination of the bits label and the bits number. For example, "monday tuesday friday" "monday 2 friday" -- 2 is the bits position for tuesday Here the bits label or bits number can be of any order like "tuesday monday friday".
AdventNet, Inc.
141
The BITSTRING data type was deprecated in the SMIV2. (Structure of Management Information). Initially the BITSTRING defined with type value is 3. However, this was replaced with the BITS type. The BITS type is not new ASN.1 type. This is same as OCTET STRING type with a way to label individual bits. Therefore, our AdventNet API returns the type value is 4. (The type value for the OCTET STRING is 4).
Create Variable
Using SnmpVar class Consider the above example of the BITS syntax. Using bits, first a byte array should be constructed. Here since there are only 7 bits, a single byte can be used to represent this BITS value. The value of the above binary number is 01100100 or 0x64. Therefore, the bye array is as follows. byte[] array = { (byte)0x64 }; String str = new String(array); SnmpVar var = SnmpVar.createVariable(str, SnmpAPI.STRING); Using SnmpBits class Valid Usage byte[] array = { (byte)0x64 }; SnmpBits bits1 = new SnmpBits(array); String str = "01100100"; SnmpBits bits2 = new SnmpBits(str, 2); String str = "64"; SnmpBits bits2 = new SnmpBits(str, 16); Invalid Usage String str = "1234"; /p> SnmpBits bits2 = new SnmpBits(str, 2); String str = "xyz"; SnmpBits bits2 = new SnmpBits(str, 16); Using mibs package The following code snippet creates an SnmpVar object of Opaque data type using the LeafSyntax class. String mibFile = "<mib name>"; String moduleName = "DATATYPE-MIB"; String nodeName = "nodeName27"; MibOperations mibOps = new MibOperations(); mibOps.loadMibModule(mibFile); MibModule module = mibOps.getMibModule(moduleName); SnmpOID snmpoid= mibOps.getSnmpOID(nodeName); MibNode node = module.getMibNode(snmpoid); LeafSyntax syntax = node.getSyntax(); String value = "monday 2 friday"; SnmpVar snmpvar = syntax.createVariable(value);
AdventNet, Inc.
142
1. The getVarObject() method returns the OCTET STRING value as String object. String obj = (String)snmpstring.getVarObject(); 2. The toValue() method returns the OCTET STRING as String object. String obj = (String )snmpstring.toValue(); 3. The toBytes() method returns OCTET STRING as a byte array. byte[] array = snmpstring.toBytes(); This byte array contains the following value. array[0] = 0x64; 4. The toByteString() method returns string with each of the bytes in the OCTET STRING in hexadecimal form. String bytestring = snmpstring.toByteString(); This string will contain the value "64". These are the hexadecimal representation of each of the bytes. 5. The toString() method returns OCTET STRING as a printable string form. String value = snmpstring.toString(); This string contains the ASCII representation of the value 0x64. 6. The toTagString() method returns the OCTET STRING value with tag of "STRING" attached to it. This string contains the ASCII representation of the value 0x64. String tagstring = snmpstring.toTagString(); This string contains the value "STRING: ". Using mibs package The toString() and toByteString() value of the variable as String. methods of the MibOperations class are used to retrieve the
The following commands retrieve the value of the created variable. String value = mibOps.toString(snmpvar, snmpoid); This string contains the value "monday(1) , tuesday(2) , friday(5)". String value = mibOps.toString(snmpvarbind);
AdventNet, Inc.
143
This string contains the value "nodeName27:-->monday(1) , tuesday(2) , friday(5)". String value = mibOps.toByteString(snmpvar, snmpoid); This string contains the value "monday(1) , tuesday(2) , friday(5)". String value = mibOps.toByteString(snmpvarbind); This string contains the value "nodeName27:-->monday(1) , tuesday(2) , friday(5)". String value = mibOps.toString(snmppdu); This string contains the following value. SNMP PDU (type unknown/unspecified) SNMP Version: Version 1 Remote Port: 0 Community: null Request ID: 0 Timeout: 0 Retries: 0 Error Status: no error SNMP PDU Variable Bindings: Object ID: .iso.org.dod.internet.private.enterprises.adventnet.snmpMIB.allNodes.nodeName27 STRING: monday(1) , tuesday(2) , friday(5) String value = mibOps.toByteString(snmppdu); This string contains the following value. SNMP PDU (type unknown/unspecified) SNMP Version: Version 1 Remote Port: 0 Community: null Request ID: 0 Timeout: 0 Retries: 0 Error Status: no error SNMP PDU Variable Bindings: Object ID: .iso.org.dod.internet.private.enterprises.adventnet.snmpMIB.allNodes.nodeName27 STRING: monday(1) , tuesday(2) , friday(5) String value = mibOps.toTagString(snmpvarbind); This string contains the following value. Object ID: .iso.org.dod.internet.private.enterprises.adventnet.snmpMIB.allNodes.nodeName27 STRING: monday(1) , tuesday(2) , friday(5) Note: In high-level API, these objects do not have separate classes because they are handled internally.
AdventNet, Inc.
144
Textual Conventions
DateAndTime MacAddress
While designing a MIB module, it is often useful to define new types similar to those defined in the SMI. These new types with different names, a similar syntax, and a more precise semantics are termed as textual conventions. The textual convention objects do not need separate classes because they are resolved into base data types. The textual convention objects are handled internally in the mibs package. AdventNet SNMP API supports the MacAddress and DateAndTime, according to their definitions.
AdventNet, Inc.
145
Overview
Objects defined using a textual convention are always encoded by means of the rules that define their primitive type. The ASN.1 macro, TEXTUAL-CONVENTION, is used to concisely convey the syntax and semantics of a textual convention. The macro construct for textual convention and an example is given below. ucName TEXTUAL-CONVENTION [DISPLAY-HINT Text] [STATUS Status] DESCRIPTION Text [REFERENCE Text] SYNTAX Syntax MacAddress ::= TEXTUAL-CONVENTION DISPLAY-HINT "1x:" STATUS current DESCRIPTION "Represents an 802 MAC address represented in the 'canonical' order defined by IEEE 802.1a, i.e., as if it were transmitted least significant bit first, even though 802.5 (in contrast to other 802.x protocols) requires MAC addresses to be transmitted most significant bit first." SYNTAX OCTET STRING (SIZE (6)) DISPLAY-HINT Clause The DISPLAY-HINT clause defines how the value of an instance of an object with the syntax defined using this textual convention should be displayed. If the syntax of the TEXTUAL-CONVENTION has an underlying primitive type of INTEGER, the DISPLAY-HINT consists of an integer-format specification, containing two parts. <intDisplayHint> = "d" ["-" number] | <singleChar> <singleChar> = o | x | b The hint can be a single character for the display format, 'x' for hexadecimal, 'd' for decimal, 'o' for octal and 'b' for binary. For displaying the value in the decimal format, the "d" can be followed by a hyphen and a decimal number, which defines the implied decimal point for the value. If the syntax of the TEXTUAL-CONVENTION has an underlying primitive type of OCTET STRING, <octetDisplayHint> = number <displayFormat> [<sepChar>] number <displayFormat> [<sepChar> [<repTermChar>]] number - unsigned integer <displayFormat> - d | a | o | x <sepChar> - separator character: any character except * and decimal digit <repTermChar> - repeat terminator character: any character other than * and decimal digit Example for DISPLAY-HINT is "2a:" where 2 is the number a is the display format : is the separator character
AdventNet, Inc.
146
Displaying the Value in the DISPLAY-HINT Format If you need to print the value in the DISPLAY-HINT, format, the method enableDisplayHint(boolean) in the MibOperations class must be set to true. MibOperations mibOps = new MibOperations(); mibOps.loadMibModules(mibFile); SnmpOID oid = mibOps.getSnmpOID("nodeName"); MibNode node = mibOps.getMibNode(oid); LeafSyntax = node.getSyntax(); SnmpVar var = syntax.createVariable("displaytest"); If the syntax of the node is a TC whose base syntax is INTEGER/Integer32 and the DISPLAY-HINT is "d-2", SnmpVar var = syntax.createVariable("12345"); mibOps.enableDisplayHint(true); String outDisplayStr = mibOps.toString(var,oid); Here outDisplayStr is 123.45. If the method enableDisplayHint(boolean) is not called or if the boolean is set to false, the outDisplayStr is 12345. Refer the Integer32 section for more information on displaying integer values. If the syntax of the node is a TC whose base syntax is OCTET STRING and the DISPLAY-HINT is "2a:", SnmpVar var = syntax.createVariable("displaytest"); mibOps.enableDisplayHint(true); String outDisplayStr = mibOps.toString(var,oid); Here, the outDisplayStr is di:sp:la:yt:es:t: If the method enableDisplayHint(boolean) is not called or if the boolean is set to false, the outDisplayStr is displaytest. Refer the OCTET STRING section for more information on displaying String values.
AdventNet, Inc.
147
DateAndTime
DateAndTime is a standard Textual Convention which is defined in the SNMPv2-TC. DateAndTime is resolved to base data type OCTET STRING. The DISPLAY-HINT format for DataAndTime is given as follows. DISPLAY-HINT "2d-1d-1d,1d:1d:1d.1d,1a1d:1d" The date-time specification is as follows. Field 1 2 3 4 5 6 7 8 9 10 Octets 1-2 3 4 5 6 7 8 9 10 11 Contents year month day hour minutes seconds (use 60 for leapsecond) deci-seconds direction from UTC hours from UTC minutes from UTC Range 0..65536 1..12 1..31 0..23 0..59 0..60 0..9 '+' / '-' 0..13 0..59
AdventNet, Inc.
148
Valid Usage SnmpVar snmpvar = syntax.createVariable("'07:D2:09:03:0C:14:20:03:2B:07:00'");//hex format, length 11 bytes SnmpVar snmpvar = syntax.createVariable("'07:D2:09:03:0C:14:20:03'");//hex format, length 8 bytes SnmpVar snmpvar = syntax.createVariable("2002-9-21,13:53:32.3,7:0");//string format, length 11 bytes SnmpVar snmpvar = syntax.createVariable("2002-921,13:53:32.3");//string format, length 8 bytes
Note: The hex value should be enclosed with the single quotes.
If the value is in any of the above formats, the value is recognized as DateAndTime value. In the first format, each octets separated by colon is considered as a byte and these bytes are stored in a byte array of length 8 or 11. If the value is in the second format, the value is translated to hex string based on DISPLAY-HINT and the bytes are stored in the byte array.
The following commands retrieve the value of the created variable. String value = mibOps.toString(snmpvar, snmpoid); This string contains the value "2002-9-3,12:20:32.3,+5:30". String value = mibOps.toString(snmpvarbind); This string contains the value "hrSystemDate:-->2002-9-3,12:20:32.3,+5:30". String value = mibOps.toByteString(snmpvar, snmpoid); This string contains the value "2002-9-3,12:20:32.3,+5:30". String value = mibOps.toByteString(snmpvarbind); This string contains the value "hrSystemDate:-->2002-9-3,12:20:32.3,+5:30". String value = mibOps.toString(snmppdu); This string contains the following value. SNMP PDU (type unknown/unspecified) SNMP Version: Version 1 Remote Port: 0 Community: null Request ID: 0 Timeout: 0 Retries: 0
AdventNet, Inc.
149
Error Status: no error SNMP PDU Variable Bindings: Object ID: .iso.org.dod.internet.mgmt.mib-2.host.hrSystem.hrSystemDate STRING: 2002-9-3,12:20:32.3,+5:30 String value = mibOps.toByteString(snmppdu); This string contains the following value. SNMP PDU (type unknown/unspecified) SNMP Version: Version 1 Remote Port: 0 Community: null Request ID: 0 Timeout: 0 Retries: 0 Error Status: no error SNMP PDU Variable Bindings: Object ID: .iso.org.dod.internet.mgmt.mib-2.host.hrSystem.hrSystemDate STRING: 2002-9-3,12:20:32.3,+5:30 String value = mibOps.toTagString(snmpvarbind); This string contains the following value. Object ID: .iso.org.dod.internet.mgmt.mib-2.host.hrSystem.hrSystemDate STRING: 2002-9-3,12:20:32.3,+5:30
AdventNet, Inc.
150
MacAddress
MacAddress is a standard TEXTUAL-CONVENTION defined in SNMPv2-TC. MacAddress is resolved to the base datatype OCTET STRING. The DISPLAY-HINT format for MacAddress is given as follows. DISPLAY-HINT "1x:"
Create Variable
Using mibs package For creating a value for a node, the createVariable() method in the LeafSyntax class is used. The MacAddress value should be six bytes. Each byte should be separated by colon(:) and the value should be enclosed in single quotes. The following code snippet creates an SnmpVar object of MacAddress type using the LeafSyntax class. String mibFile = "<mib name>"; String moduleName = "TOKENRING-MIB"; String nodeName = "dot5UpStream"; MibOperations mibOps = new MibOperations(); mibOps.loadMibModule(mibFile); MibModule module = mibOps.getMibModule(moduleName); SnmpOID snmpoid = mibOps.getSnmpOID(nodeName); MibNode node = module.getMibNode(snmpoid); LeafSyntax syntax = node.getSyntax(); String value = "a:b:c:d:e:f"; SnmpVar snmpvar = syntax.createVariable(value);
The following commands retrieve the value of the created variable. String value = mibOps.toString(snmpvar, snmpoid); This string contains the value "0a 0b 0c 0d 0e 0f". String value = mibOps.toString(snmpvarbind); This string contains the value "dot5UpStream:-->0a 0b 0c 0d 0e 0f". String value = mibOps.toByteString(snmpvar, snmpoid); This string contains the value "0a 0b 0c 0d 0e 0f". String value = mibOps.toByteString(snmpvarbind); This string contains the value "dot5UpStream:-->0a 0b 0c 0d 0e 0f".
AdventNet, Inc.
151
String value = mibOps.toString(snmppdu); This string contains the following value. SNMP PDU (type unknown/unspecified) SNMP Version: Version 1 Remote Port: 0 Community: null Request ID: 0 Timeout: 0 Retries: 0 Error Status: no error SNMP PDU Variable Bindings: Object ID: .iso.org.dod.internet.mgmt.mib-2.transmission.dot5.dot5Table.dot5Entry.dot5UpStream STRING: 0a 0b 0c 0d 0e 0f String value = mibOps.toByteString(snmppdu); This string contains the following value. SNMP PDU (type unknown/unspecified) SNMP Version: Version 1 Remote Port: 0 Community: null Request ID: 0 Timeout: 0 Retries: 0 Error Status: no error SNMP PDU Variable Bindings: Object ID: .iso.org.dod.internet.mgmt.mib-2.transmission.dot5.dot5Table.dot5Entry.dot5UpStream STRING: 0a 0b 0c 0d 0e 0f String value = mibOps.toTagString(snmpvarbind); This string contains the following value. Object ID: .iso.org.dod.internet.mgmt.mib-2.transmission.dot5.dot5Table.dot5Entry.dot5UpStream STRING: 0a 0b 0c 0d 0e 0f
AdventNet, Inc.
152
AdventNet, Inc.
153
SNMP GET
The SNMP GET operation is used by the SNMP manager applications to retrieve one or more values from the managed objects maintained by the SNMP agent. The applications typically perform an SNMP GET request by providing the host name of the agent and one or more OIDs along with the specific instance of the OID. The agent respond with a return value or with an error. The SNMP GET operation is normally used to query the scalar variables in a MIB. Each scalar variable is identified by its OID and its instance. The instance is used to identify the specific instance of the scalar variable. It is specified by appending a ".0" to its OID. For example, if we want to perform a SNMP GET on the OID .1.3.6.1.2.1.1.3, we need to specify 1.3.6.1.2.1.3.1.3.0 to retrieve the OID's value. If the request is made without the instance value, the agent returns an error. Using High-Level API explains the usage of high-level API in performing SNMP GET operation. It also discusses about loading MIBs, single variable requests, multi variable requests, PDU splitting, getting partial data while performing multi variable requests. Using Low-Level API explains the usage of low-level API in performing SNMP GET operation.
AdventNet, Inc.
154
Following are the factors related to the SNMP GET operation. Loading MIBs Single variable request Multi variable request PDU splitting Getting partial data while doing multi variable requests
Loading MIBs
The method loadMibs() in the SnmpTarget bean is used for loading MIB files in the applications or applets. Multiple MIBs can be loaded by specifying the list of MIBs separated by a space. The loaded MIB thereafter is used by all the other beans in that application or applet.
PDU Splitting
While performing SNMP requests, the operation may fail because the huge size of the message. The maximum size of the SNMP message that the AdventNet API can encode and send is 64KB. However, this also depends on the maximum size the agent can handle. If the size exceeds the limit , then the agent sends the manager a GetResponse-PDU with the errorstatus value field "too big ". In this case, we need to split the PDU into multiple requests.
AdventNet, Inc.
155
The method setAttemptComplete(boolean) in the SnmpTarget bean allows the splitting of the PDU. By default, this method is set to false. Setting a true value to this method enables the manager application to split the varbinds into multiple request. When the request is sent, the PDU is split and sent in smaller units. The data is returned by the agent in more than one unit. If the request made is a multi variable request, then the number of varbinds per request can be set using setVarBindCount(int) method. The PDU is split accordingly with the specified number of varbinds. By default, the value is zero. If the request still fails because of the "tooBig" error, the number of varbinds is further split and the request is repeated until it succeeds.
AdventNet, Inc.
156
//Build GET Request PDU SnmpPDU pdu = new SnmpPDU(); UDPProtocolOptions option = new UDPProtocolOptions("localhost"); pdu.setProtocolOptions(option); //sets the host in which the agent is running pdu.setCommand(SnmpAPI.GET_REQ_MSG); 4. To make a query for an OID or a list of OIDs, the SnmpOID class is to be instantiated. SnmpOID is the sub class of the SnmpVar class that provides abstract methods to present a uniform interface for applications working with the SNMP variables. The OID can be given in the form x.x.x... or .x.x.x.... The OID given in the form .x.x.x.x is assumed to be fully qualified, and the OID in the form x.x.x is not fully qualified in which case the value of the SnmpAPI.getOIDPrefix() method is added to the OID as a prefix. This prefix can be changed by the user but it should be to applied across the entire application or applet. The addNull method in the SnmpPDU class adds a variable binding with the OID specified and a null variable value. Multiple OIDs can also be given as input. SnmpOID oid = new SnmpOID("1.1.0"); //Here the OID is .1.3.6.1.2.1.1.0 pdu.addNull(oid); 5. After the SnmpPDU and the OID is setup using the above methods, it should be sent over a session to the peer SNMP entity. The method syncSend(pdu) is used to send synchronous requests. The printVarBinds() methods is used to print the descriptive value of the OID and the variables. An error message is displayed if the request fails. SnmpPDU result = session.syncSend(pdu); System.out.println(result.printVarBinds()); 6. Close the session and the API thread. session.close(); api.close(); Writing applications using low-level APIs is slightly complex when compared to writing applications using high-level APIs. View the complete example present in <tutorials/lowlevelapi/SnmpGet.java>.
AdventNet, Inc.
157
SNMP GETNEXT
The SNMP GETNEXT operation is similar to the SNMP GET operation. The GETNEXT operation retrieves the value of the next OID in the tree. The GETNEXT operation is particularly useful for retrieving the table data and also for variables that cannot be specifically named. It is used for traversing the MIB tree. Unlike SNMP GET, providing the instance value as part of the OID is not mandatory. The SNMP GETNEXT operation always returns the next OID in the MIB tree regardless of whether we specify the particular instance of OID. Using High-Level API explains the usage of high-level API in performing SNMP GETNEXT operation. Using Low-Level API explains the usage of low-level API in performing SNMP GETNEXT operation.
Multiple OIDs can be set using the setObjectIDList() method and the snmpGetNextList() method is used to query the agent. The following methods can also be used for performing SNMP GETNEXT operation with multiple OIDs. snmpGetNextVariables() - returns objects of type SnmpVar. snmpGetNextVariableBindings() - returns instances of SnmpVarBind. A variable binding has both the OID and the value.
AdventNet, Inc.
158
//Build GET Request PDU SnmpPDU pdu = new SnmpPDU(); UDPProtocolOptions option = new UDPProtocolOptions("localhost"); session.setProtocolOptions(option); //sets the host in which the agent is running pdu.setCommand(SnmpAPI.GETNEXT_REQ_MSG); The rest of the steps remain the same as SNMP GET. View the complete example present in <tutorials/lowlevelapi/SnmpGetNext.java>.
AdventNet, Inc.
159
SNMP GETBULK
The GETBULK operation is normally used for retrieving large amount of data, particularly from large tables. A GETBULK request is made by giving an OID list along with a Max-Repetitions value and a Nonrepeaters value. The GETBULK operation performs a continuous GETNEXT operation based on the Max-Repetitions value. The Nonrepeaters value determines the number of variables in the variable list for which a simple GETNEXT operation has to be done. For the remaining variables, the continuous GETNEXT operation is done based on the Max-Repetitions value. In other words, the SNMP GETBULK operation does a simple GETNEXT operation for the first N variable bindings in the request and does M GETNEXT operation (continuous) for each of the remaining R variable bindings in the request list where N is the minimum of the value of the Non-Repeaters field in the request the number of variable bindings in the request
M is the Max-Repetitions field of the request R is the maximum of the number of variable bindings in the request zero
Thus the total number of varbinds in the response message is (N + M x R). Using High-Level API explains the usage of high-level API in performing the SNMP GETBULK operation. Using Low-Level API explains the usage of low-level API in performing the SNMP GETBULK operation.
The snmpGetBulkList() method of the SnmpTarget Bean can be used for the SNMP GETBULK operation. //instantiate the SnmpTarget SnmpTarget target = new Snmptarget(); //set the host in which the SNMP agent is running target.setTargetHost("localhost"); //set the OID target.setObjectID(".1.3.6.1.2.1.3.1"); //perform GETNEXT String result = target.snmpGetBulkList(); System.out.println("Response: "+result); View the complete example present in <tutorials/highlevelapi/SnmpGetBulk.java>.
AdventNet, Inc.
160
To perform an SNMP GETBULK operation, the command constant GETBULK_REQ_MSG defined in the SnmpAPI class is used. //Build GET Request PDU SnmpPDU pdu = new SnmpPDU(); UDPProtocolOptions option = new UDPProtocolOptions("localhost"); session.setProtocolOptions(option); //sets the host in which the agent is running pdu.setCommand(SnmpAPI.GETBULK_REQ_MSG); pdu.setMaxRepetitions(10); pdu.setNonRepeaters(0); //Specify OID SnmpOID oid = new SnmpOID("1.3.1"); pdu.addNull(oid); The rest of the steps will remain the same as the SNMP GET operation. View the complete example present in <tutorials/lowlevelapi/SnmpGetBulk.java>.
AdventNet, Inc.
161
Polling Data
AdventNet SNMP API supports polling of one or more variables from the remote agent. Management applications in need of SNMP polling and automatic updates can use this feature. Polling is a request-response interaction between a manager and agent. It is also used to report on behalf of a user to respond to specific user queries. The basic request-response interactions occurring between a manager and agent are get, getnext and sendtrap (trap messages from SNMP agents to one or more SNMP management applications). However, the information gathered by the management application for polling is through get and getnext requests. The frequency with which the management stations poll is called the polling frequency. The SnmpPoller bean of the high-level API can be used for polling one or more variables. The SNMP Poller bean can be used in the applications, applets and also in bean builders. The values of the variables can be plotted in Graph components like LineGraphBean, BarGraphBean provided in com.adventnet.snmp.ui package. The SnmpTable bean can be used for polling table data. To use SnmpPoller for polling, instantiate, set up properties such as host name and community and register for receiving polled data. Refer the following code snippet. poller.setObjectID("1.1.0"); //the OID to be polled poller.setPollInterval(10); //polling interval in seconds. Default is 1 second. poller.setSendTimeoutEvents(true); //to send the timeout events to the listener. ResultListener listener = new ResultListener() { public void setResult(ResultEvent evt) { System.err.println("SnmpPoller Response: "+evt.getValue(0)); } }; poller.addResultListener(listener); Refer the example applet snmpPollerDemo.java in applications directory and the example application lineGraphDemo.java in examples/uiapplications directory for plotting the polled data in LineGraph. The poller will automatically poll and generate events when responses are received. If the poll interval is not set,then the default poll interval of 1 seconds will be considered. If it is required that the poller should not start polling automatically, then setAutoActive(false) should be done. Now the poller will not start polling automatically. To start polling the data should be called. poller.restartPolling() //to start polling the SNMP data
AdventNet, Inc.
162
AdventNet, Inc.
163
AdventNet, Inc.
164
SNMP SET
The SNMP SET operation is used by the management applications and applets to modify the value of the managed object. Most of the managed objects have a default value maintained by the agent. Sometimes the applications might want to modify one or more MIB variables by using the SNMP SET operation. The applications typically perform an SNMP SET operation by providing the host name of the agent, one or more OIDs along with its instance, and the new value. The agent processes the request and assigns the new value to the MIB variable. If an error occurs, the new value is not assigned. Using High-Level API explains the usage of the high-level API in performing SNMP SET operation. Using Low-Level API explains the usage of the low-level API in performing SNMP SET operation.
Multiple OIDs have to be set using the setObjectIDList() method and snmpSetList() should be used to query the agent.
AdventNet, Inc.
165
The following method can also be used for performing SNMP SET requests with multiple OIDs. snmpSetVariables() - to create SnmpVar instance for the value and the type. If we use this method, the MIB file need not be loaded because the SnmpVar object has both the type and value.
AdventNet, Inc.
166
The variable binding is then added to the PDU. //add variable binding pdu.addVariableBinding(varbind); Now the request should be sent over a session to the peer SNMP entity. The method syncSend(pdu) is used to send synchronous requests. The printVarBinds() methods is used to print the descriptive value of the OID and the variables. An error message is displayed if the request fails. SnmpPDU result = session.syncSend(pdu); Close the session and the API thread. session.close(); api.close(); Writing applications using low-level APIs is slightly complex when compared to writing applications using high-level APIs. View the complete example present in <tutorials/lowlevelapi/SnmpSet.java>.
AdventNet, Inc.
167
135 one three five one 3 five 100 192.168.1.220/ hostName 192.168.1.220/ hostName
TAddress MacAddress
f1:f2:f3:f4:f5:f6
AdventNet, Inc.
168
AdventNet, Inc.
169
Receiving Notifications
Notifications can be received using both high-level API (Beans components) and low-level API packages. Using High-Level API explains the usage of high-level API in receiving SNMP notifications. Using Low-Level API explains the usage of low-level API in receiving SNMP notifications. Trap Performance discusses the performance of notifications.
AdventNet, Inc.
170
java.net.BindException: Address already in use Note: If the setTrapAuthEnable() method is set to true, v1 and v2c traps are authenticated with the community strings. In addition, v3 traps are also authenticated. If set to false, all the traps are received irrespective of the value of the community. The method setCommunityAuthEnable(boolean) enables or disables the authentication of community name. The default value is set to true. The method setV3AuthEnable(boolean) enables or disables the authentication of v3 traps. The default value is set to true. The methods isV3AuthEnabled() and isCommunityAuthEnabled() verifies the current status of the authentication.
The interface SnmpClient is used by applications that wish to send and receive messages asynchronously. The SnmpClient interface implements callback, authentication, and debugging functions.
AdventNet, Inc.
171
The authenticate() method should check the community received in the response PDU with the community of the particular session. The "community" argument in the authenticate() method is same as the session.community and the "pdu" argument is the received PDU. public boolean authenticate(SnmpPDU pdu, String community) { if(pdu.getVersion() == SnmpAPI.SNMP_VERSION_3) { return (!(Snmp3Message)pdu.getMsg()).isAuthenticationFailed ()); } else { return (pdu.getCommunity().equals(community)); } } The callback() method should handle the PDU received for a particular session. The "session" argument is the session for which the PDU is received. The "pdu" argument is the PDU received. The "requestID" is the request ID of the sent PDU for which the response is received. The received trap information is handled here. public boolean callback(SnmpSession session, SnmpPDU pdu, int requestID) { System.out.println("Trap received from: "+pdu.getAddress() +", community: " + pdu.getCommunity()); System.out.println("Enterprise: " + pdu.getEnterprise()); System.out.println("Agent: " + pdu.getAgentAddress()); System.out.println("TRAP_TYPE: " + pdu.getTrapType()); System.out.println("SPECIFIC NUMBER: " + pdu.getSpecificType()); System.out.println("Time: " + pdu.getUpTime()+"\nVARBINDS:"); System.out.println(pdu.printVarBinds()); System.out.println("Continues waiting to receive traps in the port "+pdu.getLocalPort() +"......."); return true; } The debugprint is used for printing any debug information. public void debugPrint(String debugOutput) { System.out.println(debugOutput); return; }
Trap Performance
AdventNet SNMP API can receive about 2000 to 2500 traps per second continuously without dropping packets. When a burst of traps is sent in a short time, it can receive more than the above-mentioned number.
AdventNet, Inc.
172
The trap performance is dependent on various factors such as the type of the OS, network traffic, etc. As a result, the trap receiver applications might not always receive all the traps. One main reason for loss of traps is the UDP buffer overflow. As of now, the trap pool is the UDP buffer. Therefore, the application gets all the traps from the UDP buffer. If the application performs some action each time it receives a trap, there is a chance that UDP buffer overflows resulting in loss of packets. One way to avoid this is to have a trap receiver that continuously receives the trap and puts it into a buffer. Then another job can be scheduled to process these traps from the buffer one at a time. This way, we can implement a buffering technique to process traps. The snmptrapd example, which uses the low-level API, adopts the callback mechanism to receive traps. The performance might be degraded if additional processes are performed within callback(). Alternatively, we can use the setCallbackthread(boolean) method of SnmpSession class to implement the callback mechanism. By default, this method is set to false. Setting it true enables to run the callback in a separate thread. This is recommended only if any significant work is to be done in the callback. Note that calling the callback from a separate thread, the performance of the receiver thread in receiving responses or traps becomes a bit poorer. The trapreceiver example, which uses the high-level API, can store the received traps in a vector and process them in the main thread instead of using the receivedTrap method. // Trap application code snippet public class trapreceiverApp extends Thread { Vector trapTable; // Remember to synchronize the enqueing and dequeing methods from this vector // Thread to continuously process the received traps and do all further manipulations. run () { // Read from the trapTable vector and do all processing and then deque. } receivedTrap (TrapEvent trap) { //Enque it in the trapTable vector and return } } View the complete example present in <tutorials/lowlevelapi/ReceiveTrap.java>.
AdventNet, Inc.
173
Sending Notifications
Sending notifications are normally the functions of the SNMP agents. This functionality should be used only for testing and simulating purposes. A full-fledged notification functionality is the responsibility of the agent. Using High-Level API explains the usage of high-level API in sending SNMP notifications. Using Low-Level API explains the usage of low-level API in sending SNMP notifications.
AdventNet, Inc.
174
//Add the Trap OID variable binding - mandatory oid = new SnmpOID(".1.3.6.1.6.3.1.1.4.1.0"); var = SnmpVar.createVariable(trapoidvalue,SnmpAPI.OBJID); ... SnmpVarBind varbind = new SnmpVarBind(oid,var); pdu.addVariableBinding(varbind); //Add additional variable bindings, if required //Send the Trap PDU SnmpSession session = new SnmpSession(api); session.open(); session.send(pdu); View the complete example present in <tutorials/lowlevelapi/Sendv2cTrap.java>.
AdventNet, Inc.
175
An SNMP table can be defined as an ordered collection of objects consisting of zero or more rows. Each row may contain one or more objects. Each object in a table is identified using the table index. A table can have a single index or multiple indices. This section explains some of the basic concepts related to SNMP tables.
AdventNet, Inc.
176
To get the value of the column tcpConnState for the last row, you have to query with the OID tcpConnState.192.168.1.78.1156.192.168.4.144.80 where 192.168.1.78 is the value of tcpConnLocalAddress for the last row, 1156 is the value of tcpConnLocalPort for the last row 192.168.4.144 is the value of tcpConnRemAddress for the last row 80 is the value of tcpConnRemPort for the last row. Also if the index is of integer type, it can be in any order. For example in a table, if the values of the index column are {1,2,3,4}, it can have values in any order say {2,4,3,1}.
Augmented Table
Augmented Table comes into picture when there is one-to-one dependency between rows of one table and rows in another table. In such cases, one table is the base and the other is the augmenting table. This might arise when a particular MIB imports another MIB and shares the same table. A classic example is IF-MIB importing the group interfaces defined in RFC 1213-MIB, where IF-MIB augments the ifTable defined in RFC 1213-MIB.
AdventNet, Inc.
177
If a manager wishes to add a row, then the entryStatus column should be set to createRequest(2). Immediately after the creation, the agent sets this object to underCreation(3). The entry remains in the underCreation(3) state until it is configured. Then its value is set to valid(1). If the status remains underCreation(3) for an abnormally long period, then the agent sets the status to invalid(4).
An existing conceptual row can be in any one of the three states, 'notReady', 'notInService', or 'active'. If the manager wishes to add a row in a single shot with values for all the columns, the status column should be given as 'createAndGo(4)'. After the creation of a row, its value is set to active(1). If a row has to be created with values for only some columns, the status column should be 'createAndWait(5)'. Also, this row with partially filled columns has the status 'notReady(3)'. The entry remains in this state until the values for all the columns is set. After all the values are set, the agent changes this value to active(1).
AdventNet, Inc.
178
Fetching Tables
An entire SNMP table from a remote agent can be retrieved either by using the High-Level API or the Low-Level API.
AdventNet, Inc.
179
To set the table OID without starting the data polling, the setTableOIDWoStart(tableOID) method can be used. The following methods of the SnmpTable class can be used to get the table data in the desired format. getColumnName(int) - gets the name of the column in the SNMP table. getColumnCount(int) - returns the number of columns in the SNMP table. getRowCount(int) - returns the number of rows in the SNMP table. getValueAt(int Row, int Column) - gets the value of a particular cell. getCellValue(String tableOID, int rowIndex, int columnIndex) - gets the value of a particular cell.
The SnmpTable class provides two methods getValueAt() and getCellValue() for getting values of a single cell. If getCellValue() is used, the tableOID need not be set separately using setTableOID(). This method is preferred when the user needs to get only one value from the table. If the entire table data is required, the getValueAt() method can be used. The isCellEditable(rowIndex, columnIndex) method checks whether the specified cell is editable. The type in which the table data is returned can also be changed using setDataType() method. By default, the getValueAt() method returns data as a String. If the table data is to be returned as a SnmpVar or SnmpVarBind object, the type can be set using setDataType(). This method can take any of the following constants. STRING DATA SNMP_VARIABLE_DATA SNMP_VARIABLE_BINDING_DATA
The following code snippet makes use of some of the above methods to retrieve the table values. StringBuffer sb = new StringBuffer(); for int i=0; i < table.getColumnCount();i ++)// print column names sb.append(table.getColumnName(i)+" \t"); System.out.println(sb.toString()); StringBuffer sb2 = new StringBuffer(); for (int i=0;i < table.getColumnCount();i++)// get number of columns for (int j=0;j < table.getRowCount();j++) // get number of rows sb2.append(table.getValueAt(j,i)+" \t"); // get the cell value System.out.println(sb2.toString()); The disadvantage with this procedure is that if we do not call Thread.sleep(5000), the data from the table is not read. This is because, the Snmp Table takes some time to fetch all the table data. The value "5000" is also arbitrary which depends on the table size. If the table is very large, this value might not be adequate leading to loss of data. Therefore, this way of retrieving data is not preferred only when the size of the table is known. View the complete example present in <tutorials/highlevelapi/SnmpGetTable.java>.
Implementing Listener
AdventNet, Inc.
180
Using Thread.sleep() can be avoided if we allow event listeners to be registered to the SnmpTable component. The SnmpTableListener interface has to be implemented in the application to respond to the changes in the SnmpTable objects. The method addSnmpTableListener(SnmpTableListener) of the SnmpTable is used for registering as a listener. The SnmpTable instance while performing requests and receiving data, generates a table event. The registered listeners get the data from the response. The following piece of code gives a brief idea about implementing the listeners. public class getSnmpTable implements SnmpTableListener { public static void main(String args[]) { //instantiate a snmp table instance SnmpTable table = new SnmpTable(); ..... ..... ..... // register this class to receive table events table.addSnmpTableListener(this); // set the tableOID in the snmp table table.setTableOID(tableOID); .... } // implement the method in the SnmpTableListener interface public void tableChanged(SnmpTableEvent tableevent) { // code goes here } }
Using SnmpAugmnetTable
SnmpAugmentTable is an extended class of SnmpTable provided for obtaining augmented tables (which has one-to-one dependency between rows of one table and rows in another table) . Augmneted table can be retrieved using similar methodology which was used for obtaining ordinary SnmpTable . SnmpAugmnetTable table = new SnmpAugmentTable(); //instantiate Snmp AugmentTable table.setTargetHost("localhost"); // set the mandatory parameters table.loadMibs("RFC1213-MIB"); // load the MIB table.setTableObjectID("ifXTable"); //set the Augment tableOID View the complete example present in <tutorials/highlevelapi/GetSnmpAugmentTable.java>.
AdventNet, Inc.
181
SnmpVar objects, the snmpGetAllVariables() method can be used and to get the data as SnmpVarBind objects, the snmpGetAllVariableBindings() method can be used. If the SnmpTarget class is used for retrieving tables, then the following methods can be made use of in applications. setObjectIDList() - sets the OIDs. snmpGetAllList() - Gets the values for the OID already set in an OID list as String[][].
To get the table data as SnmpVar objects, the snmpGetAllVariables() method can be used and to get the data as SnmpVarBind objects, the snmpGetAllVariableBindings() method can be used. Consider a table with 3 column IDs, managerHost, and managerPort. Following is the sample code to get the table values. SnmpTarget target=new SnmpTarget(); target.setTargetHost("localhost"); target.loadMibs("mib"); String[] str={"id","managerHost","managerPort"}; target.setObjectIDList(str); target.snmpGetAllList(); The snmpGetAllList() method returns the table data as a two-dimensional String array. Therefore to fetch only partial table data, the required column OIDs can be set in setObjectIDList() and snmpGetAllList() can be performed.
If the columnOIDs are .1.3.6.1.4.1.2.2.1.1, .1.3.6.1.4.1.2.2.1.2, .1.3.6.1.4.1.2.2.1.3, to get the table data the following code snippet can be used. SnmpAPI api = new SnmpAPI(); SnmpSession session = new SnmpSession(api); SnmpPDU pdu = new SnmpPDU(); UDPProtocolOptions option = new UDPProtocolOptions("localhost"); pdu.setProtocolOptions(option); //sets the host in which the agent is running SnmpOID[] oids = new SnmpOID[3]; oids[0]=new SnmpOID(".1.3.6.1.4.1.2.2.1.1");
AdventNet, Inc.
182
oids[1]=new SnmpOID(".1.3.6.1.4.1.2.2.1.2"); oids[2]=new SnmpOID(".1.3.6.1.4.1.2.2.1.3"); for(int i=0;i<3;i++) { pdu.addnull(oids[i]); } pdu.setCommand(SnmpAPI.GETNEXT_REQ_MSG); //send PDU SnmpPDU result = session.syncSend(pdu); System.out.println(result.printVarBinds() + "\n"); View the complete example present in <tutorials/lowlevelapi/FetchTable.java>
AdventNet, Inc.
183
To fetch the second row from the above table, use the following code snippet. table.loadMibs("mib file"); table.setTableOID("tableOID"); //sets the table OID. table.getRow(2); //fetches the second row. This returns an array of SnmpVarBinds of data. Alternatively, if the instance value of the row to be fetched is known, say 6 is the instance value of the second row, the getRow method returns a String array of row data. table.loadMibs("mib file"); table.getRow("tableOID", "6") //sets the table OID and fetches the row data for the second row with index 6 View the complete example present in <tutorials/highlevelapi/GetRow.java>. Using SnmpTarget Class The list of OIDs (i.e the column name along with the row index) has to be first set in the method setObjectIDList() of the SnmpTarget class. Then, the snmpGetList() is used to fetch the entire row data. ID 3 6 8 12 managerHost localhost server printer switch 161 1030 8001 8080 managerPort
For example to fetch the second row of this sample table, the following piece of code is used.
AdventNet, Inc.
184
SnmpTarget target = new SnmpTarget(); String str = {"id.6", "managerHost.6, "managerPort.6"}; target.setObjectIDList(str); String result [] = target.snmpGetList();
If the columnOIDs are .1.3.6.1.4.1.2.2.1.1, .1.3.6.1.4.1.2.2.1.2, .1.3.6.1.4.1.2.2.1.3, following is the code to fetch the values for the second row in the table. SnmpAPI api = new SnmpAPI(); SnmpSession session = new SnmpSession(api); SnmpPDU pdu = new SnmpPDU(); UDPProtocolOptions option = new UDPProtocolOptions("localhost"); pdu.setProtocolOptions(option); //sets the host in which the agent is running SnmpOID[] oids = new SnmpOID[3]; oids[0]=new SnmpOID(".1.3.6.1.4.1.2.2.1.1.6"); oids[1]=new SnmpOID(".1.3.6.1.4.1.2.2.1.2.6"); oids[2]=new SnmpOID(".1.3.6.1.4.1.2.2.1.3.6"); for(int i=0;i<oids.length;i++) { pdu.addNull(oids[i]); } pdu.setCommand(SnmpAPI.GET_REQ_MSG); try { session.open(); } catch (SnmpException e ) { System.err.println("Error opening socket: "+e); } try { session.syncSend(pdu); } catch (SnmpException ex) { System.err.println("Error sending SNMP request: "+ex); } View the complete example present in <tutorials/lowlevelapi/GetRowData.java>.
AdventNet, Inc.
185
To fetch the data of the second column (ManagerHost) in the above sample table, the following code snippet can be used. table.loadMibs("mib file"); table.setTableOID("tableOID"); table.getColumn(1) // 1 represents the position of the column in the table. or table.loadMibs("mib file"); table.getColumn("managerHost"); can be used. These methods return a String array of column data. View the complete example present in <tutorials/highlevelapi/GetColumn.java>. Following is another way of fetching data for more than one column. table.loadMibs("mib file"); String[] str={"managerHost", "managerPort"}; table.setObjectIDList(str); // set the column OIDs whose values are required. table.addSnmpTableListener(listener);//register the listeners that need to get the column data. The column data can now be received in the tableChanged() method.
AdventNet, Inc.
186
For example, to fetch the second column managerHost of this sample table, the following piece of code can be used. SnmpTarget target = new SnmpTarget(); String[] str = {"managerHost"}; target.setObjectIDList(str); String result [] = target.snmpGetAllList(); This fetches all the data in the second column of the table namely localhost, server, printer, and switch. Similarly, data for more than one column can also be retrieved by including the respective column name(s) in the ObjectIDList. The snmpGetAllVariables() or snmpGetAllVariableBindings() methods can be used to get the column data, if it is required as an SnmpVar or SnmpVarBind object.
If the columnOIDs are .1.3.6.1.4.1.2.2.1.1, .1.3.6.1.4.1.2.2.1.2, .1.3.6.1.4.1.2.2.1.3, following code gets the second column(managerHost). SnmpAPI api = new SnmpAPI(); SnmpSession session = new SnmpSession(api); SnmpPDU pdu = new SnmpPDU(); UDPProtocolOptions option = new UDPProtocolOptions("localhost"); pdu.setProtocolOptions(option); //sets the host in which the agent is running SnmpOID oid = new SnmpOID(".1.3.6.1.4.1.2.2.1.2"); pdu.setCommand(SnmpAPI.GETNEXT_REQ_MSG); session.open(); session.syncSend(pdu);
SnmpOID oid = new SnmpOID(".1.3.6.1.4.1.2.2.1.2"); pdu.addNull(oid); pdu.setCommand(SnmpAPI.GETNEXT_REQ_MSG); try{ session.open(); session.syncSend(pdu); } catch(SnmpExeption e) { System.err.println("Error opening socket or sending SNMP request: "+e); } View the complete example present in <tutorials/lowlevelapi/GetColumnData.java>.
AdventNet, Inc.
187
AdventNet, Inc.
188
index.addElement(new Integer("2")); index.addElement(new Integer("3")); table.setColumnsPolled(index); //sets the columns that need to be polled table.setTableOID("tableOID"); //sets the table OID and starts polling table.addSnmpTableListener(listener); //registers listener for table changes The columns that are set will only be polled and the data is received in the tableChanged() method.
AdventNet, Inc.
189
AdventNet, Inc.
190
AdventNet, Inc.
191
For example, the following code snippet is used to change the managerHost column value 'switch' to a new value 'value' where the numeric OIDs for these columnOIDs be .1.3.6.1.4.1.2.2.1.1, .1.3.6.1.4.1.2.2.1.2, .1.3.6.1.4.1.2.2.1.3. SnmpPDU pdu=new SnmpPDU(); pdu.setCommand(SnmpAPI.SET_REQ_MSG); SnmpOID oid=new SnmpOID(".1.3.6.1.4.1.2.2.1.2.6"); SnmpVar var=SnmpVar.createVariable("value",SnmpAPI.STRING); SnmpVarBind varbind = new SnmpVarBind(oid, var); pdu.addVariableBinding(varbind); session.syncSend(pdu); View the complete example present in <lowlevelapi ModifyTable.java>.
AdventNet, Inc.
192
Adding a Row
To add a new row to a SNMP table from the manager, the table should be an SMIv1 table with EntryStatus column defined or a SMIv2 table with RowStatus column defined in it. For more information on EntryStatus and RowStatus, refer SNMP Table Basics. To add a row to a SNMP table, both High-Level API and Low-Level API can be used.
For SMIv2 Tables While creating a row, either createAndGo(4) or createAndWait(5) can be given to the RowStatus column depending on the number of columns for which values are to be set. To add a row with partially filled columns, the RowStatus column should be given as createAndWait(5). This value is changed by the agent as notReady(3). Let us now add a row to the sample table. ID 1 2 3 4 managerHost localhost server printer switch managerPort 161 1030 8001 8080
The essential prerequisite is the table should have the rowStatus column defined in it. ID 1 2 3 4 managerHost localhost server printer switch managerPort 161 1030 8001 8080 rowStatus 1 1 1 1
In this table to add the fifth row with ID = 5, managerHost =webserver, and managerPort=1080, the following code can be used. SnmpTable table = new SnmpTable(); String oidlist = {"managerHost.5", "managerPort.5", "rowStatus.5"}; String values ={ "webserver", "1080", "4"}; table.addRow( false, oidlist, values); Note that the value of "4" (creatAndGo) to the rowStatus column indicates that the new row is added in a single shot. Subsequently, the rowStatus value is changed to "1" indicating the active state. The modified table is shown below.
AdventNet, Inc.
193
ID 1 2 3 4
rowStatus 1 1 1 (4)1
Assume that we want to add another row with ID = 6, managerHost = backupserver, and with managerPort value not known. We can add the row by giving the rowStatus value to "5" (createAndWait). The modified table is shown below. ID 1 2 3 4 5 NULL managerHost localhost server printer switch webserver NULL managerPort 161 1030 8001 8080 1080 NULL rowStatus 1 1 1 1 1 notReady(3)
The value notReady(3) in the sixth row of the rowStatus column indicates that the row is not ready to be used by the manager because it needs some more data to be made active. Subsequently, when the managerPort value in the sixth row is filled in (say by a SET operation to that particular cell), the rowStatus value is changed by the agent to active state. For SMIv1 Tables Consider a table that has an EntryStatus column. To add a new row to the table with ID= 5, managerHost =webserver, and managerPort=1080, the following code can be used. SnmpTable table = new SnmpTable();> String oidlist = {"managerHost.5", "managerPort.5", "entryStatus.5"}; String values ={ "webserver", "1080", "2"}; table.addRow( true, oidlist, values); The EntryStatus value 2 stands for createRequest. After row creation, this value is set to underCreation(3). The entry remains in this state until the entry is configured, the status is then set to valid(1). If there is a delay in configuring the entry, that is, if the status remain underCreation(3) for a long time, the agent sets the status to invalid(4). View the complete example present in <tutorials/highlevelapi/AddRow.java>.
The following code snippet creates SnmpOID[] for the columnOIDs to add a row to this table with index 15 where the numeric OIDs for these columnOIDs are .1.3.6.1.4.1.2.2.1.1,.1.3.6.1.4.1.2.2.1.2, .1.3.6.1.4.1.2.2.1.3, and .1.3.6.1.4.1.2.2.1.4.
AdventNet, Inc.
194
SnmpOID oid[]=new SnmpOID[4]; oid[1]=new SnmpOID(".1.3.6.1.4.1.2.2.1.1.15"); oid[2]=new SnmpOID(".1.3.6.1.4.1.2.2.1.2.15"); oid[3]=new SnmpOID(".1.3.6.1.4.1.2.2.1.3.15"); oid[4]=new SnmpOID(".1.3.6.1.4.1.2.2.1.4.15"); The following code creates the SnmpVar objects with the value and the type of the value. SnmpVar var[]=new SnmpVar[4]; var[0]=SnmpVar.createVariable("15",SnmpAPI.INTEGER); var[1]=SnmpVar.createVariable("switch2 quot;,SnmpAPI.STRING); var[2]=SnmpVar.createVariable("9000",SnmpAPI.INTEGER); var[3]=SnmpVar.createVariable("4",SnmpAPI.INTEGER); // the value 4 refers to createAndGo. The following code creates SnmpVariableBindings using this SnmpOID and SnmpVar and adds it to the PDU using addVariableBinding(). for(int i=0;i<oid.length;i++){ SnmpVarBind varbind=new SnmpVarBind(oid[i],var[i]); pdu.addVariableBinding(varbind); } Then perform session.syncSend(pdu) to add a new row to the table. Now the rowStatus column value is changed to active(1) by the agent. While creating a row, either createAndGo(4) or createAndWait(5) can be given to the RowStatus column depending on the number of columns for which values are to be set. Add a row with partially filled columns, set the value of the rowStatus column to 5 (createAndWait). This value is changed by the agent as notReady(3). After all the column values are set, the rowStatus value is changed by the agent to active(1). For SMIv1 tables The procedure for adding a row for SMIv1 tables using low-level API is the same as that of SMIv2 tables. However, the EntryStatus column should be set to 2 (createRequest). After the creation of row, this value is set to underCreation(3). The entry remains in this state until the entry is configured and then the status is set to valid(1). If there is a delay in configuring the entry, then the agent sets the status to invalid(4). View the complete example present in <tutorials/lowlevelapi/AddRowSMIv2.java>.
AdventNet, Inc.
195
Deleting a Row
To delete a row from an SNMP table, the table should be a SMIv1 table with EntryStatus column defined or a SMIv2 table with RowStatus column defined. For more information on EntryStatus and RowStatus, refer SNMP Table Basics. To delete a row in an SNMP table, both High-Level API and Low-Level API can be used.
To delete the fourth row in the sample table, the following piece of code can be used. SnmpTable table = new SnmpTable( ); table.deleteRow(rowStatus.4) This deletes the fourth row of the table having the index value "4". Note that the method deleteRow takes the "index value" as the argument and not the serial number of the rows. ID 3 4 5 6 managerHost localhost server printer switch managerPort 161 1030 8001 8080 rowStatus 1 1 1 1
Assuming we have another table with the above index values, the table.deleteRow deletes the second row of the table and not the fourth row. From SMIv1 tables To delete a row in a SMIv1 table, the entryStatus value should be set to 'Invalid(4)'. The deleteRow method does this internally and we need to give only the entryStatus.index OID.
AdventNet, Inc.
196
To delete the second row with index 4 in the sample table, the following code can be used. table.deleteRow(entryStatus.4); View the complete example present in <tutorials/highlevelapi/DeleteRow.java>.
AdventNet, Inc.
197
To get table name we need a minimum of one column OID and the corresponding MIB file. The following piece of code uses the MibOperations class of the mibs package to identify the table name. SnmpTarget target = new SnmpTarget(); // instantiate the SnmpTarget bean String oid = ("column OID"); // set the column OID target.setMibModules("MIB file Name"); // load the MIB MibOperations mibops = target.getMibOperations(); SnmpOID rootoid = mibops.getSnmpOID(oid); MibNode node = mibops.getMibNode(rootoid); MibNode tnode =node.getParent().getParent(); System.out.println("Table name is :"+tnode.getLabel()); The following piece of code gets the index of the table. SnmpTarget target = new SnmpTarget(); // instantiate the SnmpTarget bean String oid = ("column OID"); // set the column OID target.setMibModules("MIB file Name"); // load the MIB MibOperations mibops = target.getMibOperations(); SnmpOID rootoid = mibops.getSnmpOID(oid); MibNode node = mibops.getMibNode(rootoid); Vector indices = null; indices = node.getIndexes(target.getMibOperations()); if(indices !=null) { for(int i=0; i<indices.size();i++) { System.out.println("Table Index name is:"+indices.elementAt(i)); } } else { System.out.println("Invalid column OID"); }
AdventNet, Inc.
198
The various errors and exceptions that are generated while using AdventNet SNMP APIs are detailed in this section.
AdventNet, Inc.
199
Error Handling
If any request fails during SNMP communications, the response for that request is null. In such cases the error message are set. The getErrorString() and getErrorCode() methods are provided in the SnmpTarget, SnmpRequestServer, SnmpTable, and SnmpPoller classes for handling the error messages. The getErrorString() method is used to get the error string corresponding to the error and getErrorCode() is used to get the error code corresponding to the error string. The getErrstat() method returns the standard SNMP error codes. The following are the error codes and their corresponding error status. The getError() method returns the error string corresponding to the error code present in the SNMP packet. Error Code 0 1 2 3 4 5 6 7 8 10 11 12 13 14 15 16 17 18 Error Status noError tooBig noSuchName badValue readOnly genErr noAccess wrongType wrongLength wrongValue noCreation inconsistentValue resourceUnavailable commitFailed undoFailed authorizationError notWritable inconsistentName
While sending a synchronous request using SnmpTarget Bean, an error that has occurred can be found by checking the response value. In case of timeouts or other conditions, the response for the request is null and the error messages are set. In such cases, the error string and the error code can be obtained. SnmpTarget target=new SnmpTarget(); target.setTargetHost("localhost"); target.setObjectID("1.5.0"); String result=target.snmpGet(); if( result != null ) System.out.println("Result :"+result); else System.out.println("Error :"+target.getErrorString());
AdventNet, Inc.
200
While sending an asynchronous request using SnmpRequestServer, the timeout events are not sent to the registered listeners unless the setSendTimeoutEvents(true) method is called. In SnmpRequestServer, the error string is set in the response-PDU. The error conditions can be handled as explained below. public void setResult(com.adventnet.snmp.beans.ResultEvent e) { SnmpPDU pdu=(SnmpPDU)e.getResponse(); if(pdu!=null){ System.out.println(pdu.printVarBinds()); } else{ System.out.println(e.getErrorString()); } } The getErrindex() method returns the index at which the error has occurred. This index starts from one. All the error codes that are listed in the table are standard SNMP error codes. These error codes are defined in RFC1157 and RFC1905.
AdventNet, Inc.
201
NumberFormatException
2 3 4 5 6
AdventNet, Inc.
202
This is set when the security exception is thrown while connecting to a remote host.
This is set when the class SnmpAPI is not initialized. This is set when an invalid version is specified on the target. This is set when the agent returns an empty VarBind. This is set when the remote IP address is not specified.
Invalid Version Number Agent Returned Empty Varbind(s) Remote IP address not specified.
This is set when an invalid context name is specified. This is a v3 error code constant.
Invalide context ID
This is set when an invalid context ID is specified. This is a v3 error code constant.
10
Unknown Error Input Output Error While sending PDU Request Timed Out
This is set when an unknown error not listed in the code occurs. This is set when an IO Error occurs while connecting to a remote host. This is set when the agent timesoutwithout any response after the request.
11 12
13 14
This is set when the Mib-Node is not MIB node unavailable for SnmpRequestServer available for a specified OID during a SET OID request. OID not a leaf node. SnmpRequestServer This is set when an OID is not a leaf node.
AdventNet, Inc.
203
S.No. 15 16 17 18 19
Error Messages Error creating variable Invalid generic type for trap Invalid Non-Repeaters value Discover failed Time Synchronization failed
When it occurs This is set when an error occurs while SnmpRequestServer creating a variable. This is set when an invalid generic type SnmpTarget value is specified. This is set when an invalid Nonrepeater SnmpTarget value is specified. SnmpServer This is set when discovery fails. SnmpServer This is set when Time Synchronization fails.
Classes
AdventNet, Inc.
204
Error in open
10
11
12
AdventNet, Inc.
205
S.No.
13 14 15
16
When it occurs security.provider.2=com.sun.crypto.provider.SunJCE This is set while sending SNMP requests from Error in sending pdu applets. This error occurs when unable to write to the TCP Socket. This is set when unable to send the SNMP packet. IO error sending PDU This error occurs in applications and not applets. Invalid OID Format This is set when the OID specified is not correct. This is set when the security level specified is not supported by the agent. This error is reported by the agent with its first usmStatsUnsupportedSecurityLevel varbind containing the OID ".1.3.6.1.6.3.15.1.1.1.0" and the value is a Counter giving the number of packets that have been dropped because of this error. This is set when the engineTime specified is not within the timeWindow of agent. The engineTime is considered not within the timeWindow if any of the following is true. 1. If the agent's snmpEngineBoots value is equal to 2147483647.
Error Messages
17
usmStatsNotInTimeWindows
2. If the request's snmpEngineBoots value differs from that of the agent. 3. If the difference between the SNMP request's snmpEngineTime and that of the agent is greater than 150. This error is reported by the agent with its first varbind containing the OID ".1.3.6.1.6.3.15.1.1.2.0" and the value is a Counter giving the number of packets that have been dropped because of this error. This is set when the user name specified is not present in the agent. This error is reported by the agent with its first varbind containing the OID ".1.3.6.1.6.3.15.1.1.3.0" and the value is a Counter giving the number of packets that have been dropped because of this error. This is set when the snmpEngineID specified in the request message does not match with that of the agent. This error is reported by the agent with its first varbind containing the OID ".1.3.6.1.6.3.15.1.1.4.0" and the value is a Counter giving the number of packets that have been dropped because of this error. This is set when the password specified is not correct. This error is reported by the agent with its first varbind containing the OID ".1.3.6.1.6.3.15.1.1.5.0" and the value is a Counter giving the number of packets that have been dropped because of this error. This is set when the packet is unable to decrypt on the agent side. This error occurs while querying an
18
usmStatsUnknownUserNames
19
usmStatsUnknownEngineIDs
20
usmStatsWrongDigests
21
usmStatsDecryptionErrors
AdventNet, Inc.
206
S.No.
22
23
24 25 26 27 28 29 30
31
32 33 34
35
When it occurs AuthPriv user. This error is reported by the agent with it's first varbind containing the OID ".1.3.6.1.6.3.15.1.1.6.0" and the value is a Counter giving the number of packets that have been dropped because of this error. This is set when the call to access database have timed out. This error message occurs in applets, Timed out while calling one of the four database methods of SASClient. This is set while calling the decodeMsgSecurityparams() method of Parse Error: Expected Security USMUserEntry class. This error occurs ff the tag of param string the security parameters of the received message is not an OCTET STRING. This is set if the security params field does not have Parse Header: Incorrect Paramdata a sequence tag inside the security params field. Parse Error: Expected engine id This is set if the security params field of the string message does not have a engineID field. This is set if the security params field of the Parse Error: Expected engine boots message does not have a engineBoots field. This is set if the security params field of the Parse Error: Expected engine time message does not have a engineTime field. This is set if the security params field of the Parse Error: Expected user name message does not have a userName field. This is set if the security params field of the Parse Error: Expected auth string message does not have a authParams field. This is set if the security params field of the Parse Error: Expected priv string message does not have a privParams field. This is set if the security level of the message is different from the following three messages. Unknown Error in security level Snmp3Message.NO_AUTH_NO_PRIV Snmp3Message.AUTH_NO_PRIV Snmp3Message.AUTH_PRIV This is set if the encrypted scoped PDU of the Parse Header: Incorrect Encrypted SNMP message is not encoded within a OCTET Scoped PDU Header STRING. This is set if any error occurs during the decryption Decryption failed of the encrypted scoped Data. Parse Error: unrecognized SNMP This is set if the SNMP message cannot be parsed. message This is set if an error occurs when the API sends the discovery reply message to the agent. USMUserEntry: could not send a Note:This error occurs only when AdventNet SNMP Discovery reply API is used to build the agent. If an SNMPv3 message is send to an SNMPv3 agent, it checks the validity of the userName. In case if userName is incorrect, it sends this error to the originator. The agent sends the report PDU on receiving the SNMP message. If the userName of the message is not configured in the USMUserTable of the agent, this error is sent to the originator. Note:This error occurs only when AdventNet SNMP API is used to build an agent.
Error Messages
36
AdventNet, Inc.
207
S.No.
Error Messages
When it occurs If an SNMPv3 message is send to an SNMPv3 agent, it checks whether the authParams is correct. In case if the authParams is incorrect, it sends this error to the originator. The agent developed using AdventNet SNMP API will automatically send the report PDU on receiving the SNMP message. If the authParams of the message is wrong, this error is sent to the originator. Note:This error occurs only when AdventNet SNMP API is used to build an agent. This is set if an error occurs while sending the timeSync reply. Note:This error occurs only when AdventNet SNMP API is used to build an agent.
37
38
Note: The strings in the "Error Message" column are exact. They may be appended by or prepended by other strings based on the type of exceptions.
AdventNet, Inc.
208
Java applets run in Web browsers, which often place restrictions on the capabilities of the applets for security reasons. Currently an applet in many browsers cannot communicate directly with any host on the network, except the web server from which the applet was downloaded. The AdventNet SNMP API supports access for applets in the following ways. Support through SAS (uses TCP/IP protocol) Support through HTTP Support through a generic transport provider using which users can plug-in their own transport protocol between the SAS Client and the SAS server.
AdventNet, Inc.
209
Similarly, if the applet wants to receive traps from the agent, it can register with SAS with the port on which it wants to listen for traps. The SAS opens a socket and listens for traps on that particular port on behalf of the applet and passes the traps to the applet. Apart from these, SAS can also be used for file operations, such as creating a new directory, deleting an existing directory, creating a new file, appending to an existing file, and deleting a file. From an applet, loading MIBs from a database and saving v3 information to a database is not possible if the database and the webserver are on different hosts. However, these are supported from applets in the AdventNet SNMP API by using SAS. All the database queries from the applet are forwarded to SAS. SAS queries the database to get the results and passes on the results to the applet. SAS can either be started as a standalone application or part of any other application. The SAS application can be started by giving the following command. java com.adventnet.snmp.sas.SAServer SAS is started at any random port and the port number is written to the SASPort.html file. The applet client reads this file to get the port number in which SAS is running and establishes communication to perform SNMP operations.
AdventNet, Inc.
210
The start_server.sh/bat file present in the <bin> directory of the package starts SAS and the web server. The following options can be given as command line arguments to the SAS application. "SAServer [-D] [-p port] [-d applet_directory] [-webserver_root directory] [-restrict_sockets] [session_client class] [-log_class class] [-register_client class] [-usewebserverashost] [-driver DBdriverName] [-url DBurl] [-user DBuserName] [-pass DBpassword] [-portfile filename]" where The -D option enables the debug and prints the packet dumps. -p port - specifies the port in which SAS can start. It writes the port number to the SASPort.html file. -d applet_directory - specifies the directory in which the SASPort.html file is written. By default, it is the current directory. The SASUsers subdirectory, which is used to save data from the applets, should be created under the directory specified. -webserver_root directory - specifies the root directory of the web server. -restrict_sockets - allows socket access only to SNMP UDP ports 161 and 162. -server_client class, session_client class, log_class class - implement SAServerClient, SASessionClient, and SASLogInterface interfaces. -register_client class- sets the user's implementation of the RegisterClient interface. This interface can be used by the API users to receive the traps from different agents. Whenever the SASClient calls the method reqTraps(int), (Refer "Provides a mechanism to receive traps" given below) the registerForPort(int, SocketListener) method of RegisterClient is called where SocketListener is equivalent to SASClient). The API users can write their own implementation for receiving traps and can notify the received traps to the API by calling the receivedData(ProtocolDataUnit) method of SocketListener interface. The API users should not implement the "SocketListener" interface. This is implemented by the SASession class.
AdventNet, Inc.
211
-usewebserverashost - handles the webserver host. When this is set to true, if the host is specified as "localhost" and a SNMP query is made, the query is sent to the machine where the client is running. -driver DBdriverName, -url DBurl, -user DBuserName, -pass DBpassword, - specify the database parameters. If the database connection is established in the server, all the clients can access the same database. -portfile filename - specifies the filename while starting the SAServer. On the client side, the tag should be given as PORT_FILE_NAME and the corresponding value as the filename. The method setPortFileName(String filename) in the SAServer class enables the user to configure the filename for storing the port value in which SAS has been added. The default filename is SASPort.html.
SAS can also be integrated with other applications so that it can be started as part of that application. To start the SAS from other applications, the user has to instantiate SAServer, initialize necessary variables and start the SAServer thread. First we need to instantiate the SAServer. Following are the two constructors provided by the SAServer class. //Default constructor SAServer server = new SAServer(); //Constructor for extending SAServer functionalities SAServer server = new SAServer(server_client, session_client); Here, server_client and session_client implements SAServerClient and SASessionClient respectively. They can be null, which is equivalent to the default constructor. The following command starts the SAServer thread. server.start(); The following command closes SAServer. server.close(); Using the SAS server, the applet support API offers the following services to the applets built on top of the low-level API. Provides ability to access SNMP data available with the devices in the network. Provides a mechanism to receive traps. Provides ability to create/delete files and directories and save information on files on the server. Facilitates sending and receiving application-specific data. Facilitates execution of custom Java classes on the server and getting the results. Provides ability to resolve between internet hostnames and addresses. Provides ability to access databases.
We will look at each of the above feature and see how the API supports them and how to use them in applications. Provides ability to access SNMP data available with the devices in the network The SASClient class provides a means for applets to transparently talk to SNMP devices, through the SAS server, getting around the security restrictions. Applets do not have to instantiate this class explicitly. When SnmpSession is opened, it instantiates a SASClient for communicating with the SAS server. It is explained in the following piece of code.
AdventNet, Inc.
212
try { session.open(applet); //Open session for use by the applet } catch (SnmpException e) { System.err.println("Error opening session:"+e.getMessage()); System.exit(1); } The session.open(Applet) method instantiates the SASClient. The SASClient constructor, depending on the value set in the setSASProtocol() or from the applet parameter in the HTML file, chooses the protocol it wants to communicate. The value of the protocol can be either TCP_PROTOCOL (1) or HTTP_PROTOCOL (2). TCP_PROTOCOL uses TCP/IP connection and forward the SNMP request to SAS while HTTP_PROTOCOL uses HTTP protocol and forward the request to the servlet loaded with the web server. By default, the value of the protocol is 1 (TCP/IP). The SASClient constructor reads SASPort.html file from the applet directory to get the port on which the SAS server is available. If the SASPort.html file is available in some other directory, it is specified in the applet HTML file by the SAS_PORT_DIR applet parameter. A TCP connection is established between the applet and the SAS server running on the port. When applets wish to interact with SNMP devices, they simply fill in the agent host, port, etc. in the SnmpPDU and send them over the session. SnmpPDU = new SnmpPDU(); pdu.setRemoteHost(host); pdu.setRemotePort(port); pdu.setCommand(api.GET_REQ_MSG); SnmpOID oid = new SnmpOID("1.2.0"); pdu.addNull(oid); try { SnmpPDU resp_pdu = session.syncSend(pdu); } catch (SnmpException e) { System.err.println("Sending PDU"+e.getMessage()); System.exit(1); } From the above code, it is evident that except during instantiating the SnmpSession object, applets are identical to applications. It is left to the SnmpSession object to know whether it is running in application or applet context. The SnmpSession object uses SASClient to communicate with the devices through the SAS server when it runs in applet context. Note that the SAS server can support multiple applet clients at the same time where each applet can be requesting to different devices on the network. Moreover, access to arbitrary UDP ports from the applet clients can be restricted using the restrict_sockets option available with the SAS server. This disables all but the SNMP UDP ports 161 and 162. By default, applet clients can send and receive data to any UDP port through the SAS server and request the SAS server to listen on any port for traps.
AdventNet, Inc.
213
SASClient sasClient = session.getSASClient(); if (sasClient.isConnected( ) == true) try { sasClient.reqTraps(port); } catch(IOException ioe) { System.err.println("Error " + ioe.getMessage( )); } Applets get a reference to the SASClient class used by the session using the getSASClient() method available in SnmpSession. Note that more than one applet can request the SAS server to deliver traps on the same port. When a request to forward traps on a given port is received by the SAS server, it starts listening on the port for traps. In order to receive the traps from the SAS server, applets should either implement the SnmpClient interface or poll for traps using checkResponse(). It is always best for applets to implement the callback() method in SnmpClient because it saves the overhead of polling using checkResponses(). The following piece of code illustrates this. public class trapReceiverApplet extends Applet implements SnmpClient { SnmpAPI api; // The SNMP API instance public void start() { api = new SnmpAPI( ); api.start( ); api.setDebug(true); SnmpSession session = new SnmpSession(api); session.setCallbackthread(true); session.addSnmpClient(this); int port = 162;// set port to listen for traps try { session.open(this); //Open session for use by the applet } catch (SnmpException e) { System.err.println("Error opening session:"+e.getMessage()); System.exit(1); } SASClient sasClient = session.getSASClient( ); if (sasClient.isConnected( ) == true) { try { sasClient.reqTraps(port); } catch(IOException ioe) { System.err.println("Error " + ioe.getMessage( )); } } }
AdventNet, Inc.
214
public boolean callback(SnmpSession session, SnmpPDU pdu, int reqid) { if (pdu.getCommand() == api.TRP_REQ_MSG || pdu.getCommand() == api.TRP2_REQ_MSG) { showStatus("Trap PDU received"); return true; } else { System.err.println("Non trap PDU received"); } return false; } public void debugPrint(String s) { System.err.println(s); } public boolean authenticate(SnmpPDU pdu, String community) { return true; } }
Provides ability to create/delete files and directories and save information on files on the server
Applets developed using AdventNet SNMP API can create and delete directories in addition to reading and writing into files in the web server. Applets can only perform these operations on directories and files available in the SASusers subdirectory in which SASPort.html was created by the SAS server. The SASusers directory must exist for the applet to perform these operations and the location of this directory can be specified using the -d option while starting the SAS server. The default location of the SASUsers directory is the directory from which the SAS server is started. The following methods are available in the SASClient class to perform file operations. appendFile(String filename, byte[ ] data) createDir(String directory) deleteDir(String directory) deleteFile(String filename) saveFile(String filename, byte[ ] data) Note that the file operations available with the SAS server can be disabled. If the SAS server is started with the -no_file_output option, the SAS server does not allow file operations from applet clients. Also, the directory in which the file operations are allowed can be specified using the -d option.
AdventNet, Inc.
215
SASClient sasClient = session.getSASClient(); byte[] responseData = sasClient.userSyncSend (int requestType, byte[], requestData); Here, requestType is greater than SASClient.SAS_VALID_TYPES, requestData can be any data sent by the applet client, and responseData is the response returned by the server side application. The SASClient and the SAS server pass the request and the response transparently between the applet and the userCall() method available with the SASessionClient interface. Note that only one class that implement SASessionClient can be registered with the SAS server for all applet clients and a new instance of SASessionClient class is instantiated for every applet client that connects to the SAS server.
Facilitates execution of custom Java classes on the server and getting the results
Applets can invoke methods on the SAS server using the clientCall() method available with the SASClient class. This method can be used to build application-specific functions around SAS by extending the interaction between the applet client and the SAS server. enables applet clients invokes a method in the server by using the following code. SASClient sasClient = session.getSASClient( ); byte[ ] responseData = sasClient.clientCall(byte[ ] requestData); On the SAServer side, the clientCall() method is available in SAServerClient and SASessionClient interfaces. If both interfaces are available, the SAS server calls the SAServerClient interface method first and then calls the SASessionClient method. The SAServerClient class is registered using the -server_client option and the SASessionClient class is registered using the -session_client option while starting the SAS server. Note that there is only one instance of the SAServerClient class for a SAS server while there is one instance of SASessionClient for each applet client. Therefore, server side applications that require to maintain client-specific information should implement the SASessionClient interface.
AdventNet, Inc.
216
2. closeDB() This method is to close the database connection. It throws an SQLException if the database connection cannot be closed. 3. queryDB(String queryString) This method is to query the specified database. The user should pass the SQL query string as argument. The method returns an instance of ResultSet. Currently, the database tables with all the columns of type "varchar" or "text" can only be queried. This method is equivalent to the "executeQuery(String)" method of "java.sql.Statement" class. It throws an SQLException if a database access error occurs. 4. updateDB(String updateString) This method is to update the database with new values, deleting a row, inserting a row, etc. This method is equivalent to the "executeUpdate(String)" method of "java.sql.Statement" class. It throws an SQLException if a database access error occurs.
AdventNet, Inc.
217
Extending SAS
Three interfaces namely SAServerClient, SASessionClient, and SasLogInterface are implemented to add custom functionality. Only one class of SAServerClient or SASessionClient should be registered with SAServer. If both the interfaces are registered, the value returned from the methods common to both interfaces, such as requestPDU() and responsePDU(), are overwritten. In this case, the value returned from the implementation file of SASessionClient overwrites the value returned from that of SAServerClient. These two interfaces allow far more flexibility in implementing SAS enhancements. The classes implementing the interfaces can be specified by command line options while starting the SAServer.
Interface SAServerClient
This allows instantiation of a custom class when SAS is started. The methods in this interface are the following. Method Purpose This method is called when SAServer starts. This assigns the applet directory and the webserver root directory. The applet_dir is an applet directory in which the file SASPort.html is written. SASPort.html is the file which contains the port number where the SAServer is started. This method is called when a new SASession is opened. The applet_addr is the client's address and applet_port is the client's port where the SASession is started. This method is called when the client opens a UDP port. Typically, the port is 0, which implies a system assigned UDP port. For listening traps or SNMP PDUs, a specific port can be specified. The return value is used for custom port assignment, if required. This method is called before sending any request. The PDU is sent to the agent, which can be modified as required by the custom class. For example, if the user wants to customize the request so that it is always sent to the "localhost" the following code should be used. pdu.setRemoteHost("localhost") This method is called after receiving a response on the server side. This is the response PDU from the agent, which can be modified as required. This method allows the applet client to invoke a method on the server. The corresponding method is provided in the SASClient class. Any arguments and return values need to be serialized. It returns response data to be sent to the client. This method is used when the user wishes to perform operations, such as reading the contents of a file, listing a directory, etc. This method is called while closing the applet session.
AdventNet, Inc.
218
Interface SASessionClient
This class is instantiated for each session. This allows performing custom functions for each applet session, such as caching data for an applet. This corresponds to an instance for each SASClient instance on the client. Following are the methods available in this interface. Method public void init(InetAddress applet_addr, int applet_port, SASession session); Purpose This is called when a new session is opened. This parameters applet_addr and applet_port correspond to client's address and client's port respectively. This is called when the client opens a UDP port. Typically, the port is 0, the system assigned UDP port. For listening traps or SNMP PDUs, a specific port can be specified. The return value is used for custom port assignment if required. This method is called before sending the request. The PDU is sent to the agent, which can be modified as required by the custom class. This method is called after receiving the response. This is the response PDU from the agent, which can be modified as required. This method allows the applet client to invoke a method on the server. The corresponding method is provided in the SASClient class. Any arguments and return values need to be serialized. This method is called when the session is closed. The object is de-referenced if all of its threads are stopped. This method allows the user to implement the request type. For example, if the user request type is REVERSE_DATA, the received data can be reversed and returned in this method.
Interface SasLogInterface
This class is instantiated once. This can be used to provide custom methods to redirect error and debug messages and log data. Method public void err(String err); public void dbg(String dbg); public void out(String out); Purpose This method handles the error messages. This method handles the debug messages that are generated. This method handles all stdout messages.
In SAS and SASClient, the following methods are supported. Method createDir(String dir) deleteDir(String dir) Purpose This method creates a directory with the specified relative or absolute path. This method deletes a directory with the specified relative or absolute path.
AdventNet, Inc.
219
Purpose This method deletes a file with the specified relative or deleteFile(String file) absolute path. This method requests for traps arriving on the specified reqTraps(int port) port at the SAServer. This method queries the SAServer for the host name getHostName(String address, int timeout) with the given IP Address. getHostAddress(String hostname, int This method queries the SAServer for the IP Address of timeout) the hostname supplied. This method enables users to send their own request userSyncSend(int userType, byte bytes[]) type.
Method
Interface RegisterClient
This interface can be used by the API users to receive the traps from different agents. The API users can write their own implementation for receiving traps and can notify the received traps to the SAS API. The following things need to be considered during implementation. There is only one instance of RegisterClient in the SAS API and it is static in SAServer. This instance is used by all the SASClients, who are connected to the SAServer. More than one SASClient can request for traps for the same port.
The various methods present in RegisterClient interface are: 1. registerForPort(int port, SocketListener tl) throws Exception Whenever the SASClient calls the method "reqTraps(int)" (Refer "Support through SAS >Provides a mechanism to receive traps"), this method is called where "SocketListener" is equivalent to SASClient. The received traps can be notified to the API by calling the method receivedData(ProtocolDataUnit) of SocketListener interface. The API users should not implement the "SocketListener" interface. This is implemented by the SASession class. 2. registerForPorts(int[] ports, SocketListener tl) throws Exception This method is used if the same client wants to listen for traps to a set of ports. 3. deRegisterForPort(int port, SocketListener tl) This method is used if a client wants to deregister for a particular port. 4. deRegisterForPorts(int[] ports, SocketListener tl) This method is used if a client wants to deregister for a set of ports. 5. deRegister(SocketListener tl) This method is used if the client does not want to listen for traps. This method is called if the "close" method if SASClient is called.
Interface SocketListener
There is no need for the API users to implement this interface. While implementing the RegisterClient interface if a trap is received, it should be notified to the SAS API by calling the receivedData (ProtocolDataUnit) method of SocketListener. This is implemented by SASession and whenever the receivedData method is called, the received trap is notified to SASession which in turn is notified to the client.
AdventNet, Inc.
220
The method in this interface is: receivedData(ProtocolDataUnit). API users can implement the RegisterClient interface so that they can follow their own way to receive traps. This implemented class can be specified as a command line argument while starting SAServer. Whenever a request for traps arrives at the SAServer, the method registerForPort(int portToListen, SocketListener whichListensForTraps) is called. Therefore whenever the users receive traps, they need to inform the listener by calling the method SocketListener's receivedData(ProtocolDataUnit). API users should not implement the SocketListener interface because it is implemented internally by SASession class. This receivedData(ProtocolDataUnit) method is called whenever a trap is received. Note: The SAServerClient and SASessionClient classes must support an empty constructor to allow instantiation by SAS. For all callbacks in which methods from both the SAServerClient and SASessionClient implementations are invoked, the SAServerClient implementation is called first. To allow controlling the number of SNMP clients, the return value of the open(int port) can be used. If the number returned is less than zero, a UDP port is not opened disabling SNMP communication from the applet. To minimize overhead when no PDU processing is done in the client programs, the SnmpPDU pre-processing and post-processing methods must call pdu.decode() to view the PDU data and pdu.encode() to make effective changes in the PDU. Multiple clients can request for the same trap port. Incoming traps at that port are delivered to all the clients. A client application can request for traps arriving at more than one port. The methods of RegisterClient is called from the SASession instance. Currently, only registerForPort(int SocketListener) and deRegister(SocketListener) methods are called from SASession because there is no equivalent methods in SASClient. However, these two methods are sufficient to fulfill the trap requirement. An implementation for remaining methods will be in the future releases of the API.
AdventNet, Inc.
221
If the client applet runs behind a firewall, it cannot connect to a server outside the firewall because the firewall prevents the socket connections. However, we can connect the applet to servers through HTTP.
AdventNet, Inc.
222
On the client side, the following code uses the URLConnection to send data to the server. //connect URL url = new URL("http://www.myserver.com/servlets/myservlet"); URLConnection conn = url.openConnection(); conn.setDoOutput(true); conn.setUseCaches(false); conn.setRequestProperty("Content-Type", "application/octetstream"); //Open output stream and send data OutputStream out = conn.getOutputStream(); out.flush(<); out.close(); //Open input stream and read the data back InputStream in = conn.getInputStream(); in.close() On the server side when the client calls openConnection(), the servlet's doPost() method is called. In that method, we can read the data and write back to the client.
AdventNet, Inc.
223
Provides the ability to access SNMP data available with the devices in the network
When SnmpSession is opened, it instantiates SASClient for communicating with the SAS server or HttpSnmpGWServlet depending on the parameter value specified in the HTML file. The applets need to only specify the protocol value in the HTML file. The session.open(Applet) method instantiates SASClient. The SASClient constructor, depending on the value set in the setSASProtocol() or from the parameter PROTOCOL in the HTML file, chooses the protocol it wants to communicate. The value for protocol can be either TCP_PROTOCOL (1) or HTTP_PROTOCOL (2). TCP_PROTOCOL uses TCP/IP connection and forward the SNMP request to SAS and HTTP_PROTOCOL uses HTTP and forward the request to the servlet loaded with the web server. By default, the port value is written in SASPort.html. If the user wants the port value to be written in some other file, setPortFileName(String) method in SAServer class can be used. Alternatively, while starting the SAServer, the user can enable the option "-portfile" and specify the filename. On the client side, the tag should be given as PORT_FILE_NAME and the corresponding value as the filename given on the SAServer side. In case of SAS, a TCP connection is established between the applet and the SAS server running on the port. On the other hand, in case of HTTP, a connection using HTTP is established between the applet and the servlet loaded with the web server. This connection is used for future communication with SNMP devices. By default, the value of the setSASProtocol() is 1. So we need to explicitly set the value to 2 to use the HTTP protocol for communication. Currently the equivalent of setSASProtocol() is not available for Beans components. Therefore, if the applets developed using Beans components need to use HTTP protocol for communication, we need to specify the value for the parameter PROTOCOL in the HTML file. After setting the protocol to HTTP, the communication to SNMP devices can be done in similar way as we discussed in Support Through SAS.
AdventNet, Inc.
224
Provides ability to create/delete files and directories and save information on files, on the server
Using HTTP, applets can perform operations on directories and files in the HTTPUsers directory available in the httpdemo directory. The methods for performing these operations are same as those in SAS. The following the file-related operations using HTTP. appendFile(String filename,byte[ ] data) createDir(String directory) deleteDir(String directory) deleteFile(String filename) saveFile(String filename,byte[ ] data)
Limitations
Sending and receiving application-specific data, executing custom Java classes on the server and getting the results, and resolving between internet hostnames and addresses using HTTP protocol are not supported with the current release. Currently, the servlet used for communicating with the applet is loaded using the Tomcat web server which is packaged with the AdventNet SNMP API. Details of configuring it with other web servers, such as Apache will be provided in the next release. By default, browsers such as Netscape and IE use HTTP 1.0 that does not use persistent connection. As a result, using HTTP protocol from applets is a bit slower than using the TCP/IP.
AdventNet, Inc.
225
AdventNet, Inc.
226
AdventNet, Inc.
227
Installation Notes
These are the changes made in the configuration file of the Tomcat Web Server (in tomcat/conf/server.xml file) to load the applets. The applets can use any underlying protocol for SNMP communication. The reference implementations for TCP/IP and HTTP are provided. TCP_PROTOCOL uses TCP/IP connection and forwards the SNMP request to SAS. HTTP_PROTOCOL uses HTTP protocol and forward the request to the HttpSnmpGWServlet loaded with the web server. 1. Change the default index page. < Context path="/examples" docBase="webapps/examples" crossContext="false" debug="0" reloadable="true" > </ Context > is changed to Context path=""docBase="../" crossContext="false" debug="0" reloadable="true" > </Context > 2. Change the port number. < Connector className="org.apache.tomcat.service.PoolTcpConnector" <Parameter name="handler" value="org.apache.tomcat.service.http.HttpConnectionHandler"/> <Parameter name="port" value="8080" /> </Connector > is changed to <Connector className="org.apache.tomcat.service.PoolTcpConnector" <Parameter name="handler" value="org.apache.tomcat.service.http.HttpConnectionHandler"/> <Parameter name="port" value="8282"/> </Connector> The port at which the web-server is started is changed to 8282 from 8080. 3. Log the error messages. < Logger name="tc_log" verbosityLevel = "INFORMATION" /> is changed to < Logger name="tc_log" path="logs/tomcat.log" verbosityLevel = "INFORMATION" /> This is to redirect all the error messages to the tomcat.log file in the logs directory.
AdventNet, Inc.
228
SNMP protocol standards define UDP to be used as the default protocol for communication. UDP, being a connectionless protocol, is most suitable for exchanging messages with smaller packet sizes. It is appropriate for the network management system that requires to perform quick queries on lot of devices. In case of database retrievals and updates, where the packet sizes are large, TCP might be the preferred protocol. Also developers might want to choose their own protocol for implementation, such as IPX, HTTP, TCP, Serial port communication, and so on. Users requiring more security can also implement SSL below the SNMP for secure communication. To facilitate this, AdventNet SNMP API includes a new transport provider framework, whereby the users can plug-in their own transport protocol. This framework enables the developers to implement the protocol of their choice for SNMP communication. The API implements UDP/IP as the default protocol implementation. We also provide TCP/IP as the reference implementation that uses the transport provider framework.
AdventNet, Inc.
229
2. ProtocolOptions - This interface defines some parameters that are to be implemented by the user. It contains the following API methods. Refer the javadocs files for exact syntax. getSessionId - Returns a unique session ID for each SNMP session. This needs to be implemented only for SNMPv3 module.
3. SnmpTransportPacket - This class contains the details of the ProtocolOptions used by the SNMP API and the details of message sent or received. This contains the following API methods. Refer the javadocs files for exact syntax. getProtocolOptions - Returns the transport parameters set on the transport packet for sending/receiving messages. setProtocolOptions - Sets the protocol options on SnmpTransportPacket. getProtocolData - Gets the SNMP message to be sent or received. setProtocolData - Sets the protocol data on SnmpTransportPacket.
You can also implement your own transport provider. Refer Custom Transport Provider for more information.
AdventNet, Inc.
230
2. - This interface is responsible for creating a transport session between the client and server. It contains the following API methods: (Refer the Javadocs for the exact syntax) init() - Initializes the transport session over which the data is sent/received. open() - Creates the transport session for SAS communication and returns a reference to the SessionTransportProvider object. close() - Closes the transport interface after communication is over.
You can also implement your own transport provider. Refer Custom Transport Provider for more information.
AdventNet, Inc.
231
How to plug-in your protocol implementation in the SAS transport provider framework
1. Provide implementation of the SessionTransportProvider for the protocol (say SSL) This class should provide the open(), close(), read(), and write() implementation required for SSL communication. This can be used by both the SAS server and the SAS client to set up the basic communication and transfer data. 2. Provide server side and client side implementation of the TransportProvider for your protocol - These classes should provide the client and server side implementation required for creating TransportProvider and any other protocol initializations, if required. After the TransportProvider objects are created, all further communication between the client and the server is handled by the TransportProvider. 3. Register your protocol with the client side Transport provider by including the class name of the client side implementation of the TransportProvider in the applet's HTML file. For example, if the client side implementation of the TransportProvider is com.adventnet.management.transport.TcpClientTransportImpl.java, then the HTML file would contain the following line. <PARAM NAME = "TRANSPORT_PROVIDER" VALUE="com.adventnet.management.transport.TcpClientTransportImpl">
AdventNet, Inc.
232
4. Create an instance of the server side implementation of the TransportProvider (say, com.adventnet.management.transport.TcpServerTransportImpl that implements com.adventnet.snmp.management.transport.TransportProvider) com.adventnet.management.transport.TransportProvider myProtocol = new com.adventnet.management.transport.TcpServerTransportImpl(); 5. Register the protocol with the server's transport provider. SAServer mySasServer = new SAServer(serverClient, sessionClientClass); mySasServer.setSASTransportProvider(myProtocol);
AdventNet, Inc.
233
Introduction to IPv6
IP version 6 (IPv6) is a new version of the Internet Protocol, designed as the successor to IP version 4 (IPv4) [RFC-791]. The changes from IPv4 to IPv6 fall primarily into the following categories. Expanded Addressing Capabilities: IPv6 increases the IP address size from 32 bits to 128 bits, to support more levels of addressing hierarchy, a much greater number of addressable nodes, and simpler auto-configuration of addresses. Improved Support for Extensions and Options: Changes in the way IP header options are encoded allows for more efficient forwarding, less stringent limits on the length of options, and greater flexibility for introducing new options in the future. Flow Labeling Capability: A new capability is added to enable the labeling of packets belonging to particular traffic "flows" for which the sender requests special handling, such as non-default quality of service or "real-time" service. Authentication and Privacy Capabilities: Extensions to support authentication, data integrity, and (optional) data confidentiality are specified for IPv6.
AdventNet, Inc.
234
may be represented as: 1080::8:800:200C:417A a unicast address FF01::101 a multicast address ::1 the loopback address :: the unspecified addresses An alternative form that is sometimes more convenient when dealing with a mixed environment of IPv4 and IPv6 nodes is x:x:x:x:x:x:d.d.d.d, where the 'x's are the hexadecimal values of the six high-order 16-bit pieces of the address, and the 'd's are the decimal values of the four low-order 8-bit pieces of the address (standard IPv4 representation). Examples: 0:0:0:0:0:0:13.1.68.3 0:0:0:0:0:FFFF:129.144.52.38 or in compressed form ::13.1.68.3 ::FFFF:129.144.52.38
Special IPv6 Address Types and their Use in the AdventNet SNMP API Unspecified Address
When you want to listen on the wildcard address use "::". For example, to listen for traps on all the interfaces on a IPv6 system, you can open the SnmpSession with this address.
Loopback Address
The address "::1" can be used to listen on the IPv6 loopback. This address can be used to receive/send SNMP PDUs over the IPv6 loopback interface.
Compatibility address
To send SNMP packets in IPv6 packets tunneled over IPv4, use addresses of the form "::w.x.y.z" with "w.x.y.z " being the IPv4 address.
AdventNet, Inc.
235
Dual-Stack Node
A general property of a dual-stack node is that an IPv6 socket can communicate both with an IPv4 and IPv6 peer at the transport layer (TCP or UDP) . At the native level, the IPv6 socket communicates with an IPv4 peer through an IPv4-mapped IPv6 address. The impact on the Java application are the following. There should be no change in Java application code if everything has been done appropriately. I.e., there are no direct references to IPv4 literal addresses; instead, hostnames are used. All the address or socket type information is encapsulated in the Java networking API. Through setting system properties, address type and/or socket type preferences can be set. For new applications Ipv6-specific new classes and APIs can be used.
Communication scenarios
Nodes V4 Only V4/V6 V6 Only V4 Only Possible Possible Not Possible V4/V6 Possible Possible Possible V6 Only Not Possible Possible Possible
Top row and left column represent various node types attempting to communicate.
AdventNet, Inc.
236
Internationalization
Using High-Level API Using Low-Level API
AdventNet SNMP API supports internationalization. This allows applications and applets developed using AdventNet SNMP API to be deployed in various languages without doing any changes in the code. Localized content can be added easily and the same executable can be run world wide. All the textual elements such as GUI component labels and messages can be made suitable to the locale (combination of specific language and country) of the user.
AdventNet, Inc.
237
AdventNet, Inc.
238
AdventNet, Inc.
239
AdventNet SNMP API supports logging of the messages. Using this feature, applications can log the debug messages, results, error messages, and the actions performed while querying for one or more variables from the remote agent.
AdventNet, Inc.
240
Logging Mechanism
AdventNet SNMP API supports logging of the SNMP requests. There are two types of logging that can be done from applications. Log the debug and error messages while querying for one or more variables from the remote agent. Log the actions performed in the SNMP application. This includes logging of the debug and error messages also.
To do this, applications should implement LogInterface class available in com.adventnet.utils package. The LogInterface contains the following methods. // implemented for logging debug messages public void dbg(String debug); //implemented for logging error messages public void err(String error); //implemented for logging result public void out(String out); The LogManager class from com.adventnet.utils package manages the redirecting of debug messages and error messages from the SnmpSession class to the client, which sends request. The client has to implement LogInterface in his application. When the client is registered by calling addLogClient() method, LogManager generates an unique ID and returns it to the client that registers with LogManager. This clientID should be set in the requests that are sent to the agent. In the case of low-level api's, this should be set on the SnmpPDU instance that is used in sending the request. In the case of high-level api's, this will be handled internally. Using this clientID, the LogManager will call the corresponding client's debug()/err()/out() method of the LogInterface implementation. The following code snippet shows how to implement the LogInterface in application that uses high-level API. public class client implements LogInterface{ public client() { SnmpTarget target =new SnmpTarget(); target.addLogClient(this); //sending request ....... ....... } public void dbg(String debug){ ...... } public void err(String error){ ...... } public void out(String out){ ...... } }
AdventNet, Inc.
241
The following code snippet shows how to implement the LogInterface in applications using low-level API. public class client implements LogInterface{ public client() { SnmpAPI api = new SnmpAPI(); ........ SnmpSession session = new SnmpSession(api); ....... int id = LogManager.addLogClient(this); SnmpPDU pdu =new SnmpPDU(); pdu.setClientID(id); ...... // sending request ...... ...... } public void dbg(String debug){ ...... } public void err(String error){ ...... } public void out(String out){ ...... } }
To enable this feature, addLogClient(LoggerProperties) method should be invoked. In application, if low-level api is used, then this method should be invoked from com.adventnet.utils.LogManager class. If the application uses high-level api then the same should be invoked from the class being used like SnmpTarget, SnmpRequestServer etc. LoggerProperties class should be instantiated first by invoking LoggerProperties() constructor with the first argument as the package name and the second argument as the filename. For example, if a LoggerProperties instance needs to be created for the beans package with the filename "beans.txt", then invoke LoggerProperties. loggerProp = new LoggerProperties("BEANS", "beans.txt"); The different package names with which LoggerProperties instance can be created is SNMP2, MIBS, LLAPI, BEANS, HLAPI and SNMP. Logging level can be set by invoking setLogLevel(int ) method in LoggerProperties class. The different logging level that are supported are DEFAULT, SERIOUS and CRITICAL. Static constants for the logging levels have been provided in com.adventnet.utils.LogManager class. Depending on the level, logging of messages will be done.
AdventNet, Inc.
242
The logging type should be added as a custom property to the LoggerProperties instance with the key as "LOGTYPE". DEBUG and PERF are the two logging types that are currently supported. The logging type can be added as a custom property by calling addCustomProperty("LOGTYPE", "DEBUG"); If any user implementation of Logger interface needs to be used in the application, then the implementation file with the package structure should be passed to setClassName() in LoggerProperties. We are providing a default implementation, SnmpLoggerImpl. The following code snippet shows how to enable this feature in a application that uses high-level API. public class client { public client() { ....... ....... LoggerProperties loggerProp = new LoggerProperties("SNMP", "SNMP.txt"); loggerProp.setClassName("com.adventnet.utils.SnmpLoggerImpl"); loggerProp.setLogLevel(LogManager.CRITICAL); loggerProp.addCustomProperty("LOGTYPE", "DEBUG"); SnmpTarget target =new SnmpTarget(); target.addLogClient(loggerProp); ....... ....... } } The following code snippet shows how to enable the logging feature in a application that uses lowlevel API. public class client { public client() { ...... ...... LoggerProperties loggerProp = new LoggerProperties("SNMP2", "SNMP2.txt"); loggerProp.setClassName("com.adventnet.utils.SnmpLoggerImpl"); loggerProp.setLogLevel(LogManager.CRITICAL); loggerProp.addCustomProperty("LOGTYPE", "DEBUG"); int clientID = LogManager.addLogClient(loggerProp); SnmpPDU pdu = new SnmpPDU(); pdu.setClientID(clientID); // Send the data ....... ....... } }
AdventNet, Inc.
243
Deployment Instructions
Deploying Applications Deploying Applets Deploying EJB Applications
This section details the instructions needed for deploying the applications and applets developed using AdventNet SNMP API.
AdventNet, Inc.
244
Deploying Applications
The deployed environment should have a Java Virtual Machine (JVM) installed. The JVM can be the latest version of JDK or JRE. The JFC/swing classes (swingall.jar) is also required for the deployment depending on the application developed. The application meant for deployment should have the following jars present in the <AdventNet/SNMP API/v2cjars> directory. AdventNetSnmp.jar contains the AdventNet SNMP API core SNMP beans, and the User Interface beans. AdventNetLogging.jar - It contains the AdventNet logging related classes. AdventNetRMI.jar - It is included when RMI related classes are required for deploying applications. AdventNetCorba.jar - It is included when CORBA related classes are required for deploying applications.
AdventNet, Inc.
245
Deploying Applets
Server Side:Applet class files and the necessary HTML files are to be copied to the WebServer directory. In the HTML file, the "code" parameter should point to the class file and the "Archive" parameter to AdventNetLogging.jar, AdventNetSnmp.jar, and MibBrowser.jar. SAS has to be started as separate application from the WebServer directory. Alternatively, the applet class files and the necessary AdventNet classes can be made as a JAR file and put in the web server. The HTML file can now point to this JAR file. In both the cases, SAS is to be started in the web server on any available port. The SAS port information is written to the file SASPort.html in the specified directory. Applets read the SASPort.html to find out where SAS runs and uses it for SNMP communication. Currently, the applets which uses HTTP Tunnelling for SNMP communication cannot be configured in other web servers. It can be used only along with the Tomcat web server that is distributed as part of the AdventNet SNMP API 4. Client Side:Applet viewer or any Java-enabled browser with Sun's Java plug-in. The plug-in is required to test/view the applets which use swing or JFC components. The standard browsers Netscape 4.x or IE 4.x do not support JFC classes. Applets which do not use swing components can be viewed using standard web browsers.
AdventNet, Inc.
246
WebLogic 7.0 edition WebLogic 6.1 beta edition WebLogic 5.1 edition
BEA Weblogic server is one of many EJB capable application servers in the market. These examples can easily be migrated to other EJB application servers. For the client example, this is usually done by simply changing imports for JNDI. The SNMP server startup class needs to be modified for each application server. Future releases of AdventNet SNMP will provide detailed instructions on using other EJB application servers. First, obtain and install the EJB application server: The BEA Weblogic server can be obtained from the BEA web site. Follow the instructions for application server installation. The user should follow the steps given below to successfully use the examples provided in the ejbclient directory for SNMP operations. 1. Configure the SnmpEJBServer factory: The SnmpEJBServer factory is responsible for the creation of the various SNMP Bean components required by the EJB components to perform SNMP operations. This module handles all the SNMP-specific operations, interfacing with the EJB components on one side and the SNMP agent on the other side. The user should start the SnmpEJBServer within the application server. This is done for BEA Weblogic using an SNMP server startup class that is configured in the weblogic.properties file. Refer "Plug in the startup class in the application server". However, initially the you should create a startup class to start SnmpEJBServer in the application server. This is specific to the application server you intend to use. A sample application SnmpStarter is packaged for your reference and you can modify this class if required. Compile this class in <AdventNet\SNMPAPI\reference\ejb> directory. A sample code snippet for starting the SnmpEJBServer factory is as follows. public String startup(String name, Hashtable args) throws Exception { try { SnmpEJBServerImpl factory = null; String usage = "java SnmpEJBServerImpl [-hp host:port]"; factory = new SnmpEJBServerImpl(); Environment env = new Environment(); Context ctx = env.getInitialContext(); ctx.bind(name, factory); } catch( Exception e ) { System.err.println("SnmpEJBServerImpl: "+ e.getMessage()); e.printStackTrace(); } } 2. Plug in the startup class in the application server: You need to make the desired changes in the application server's property file for plugging the startup class. For example in BEA Weblogic, the SNMP server startup class is configured using the weblogic.properties server configuration file. The configuration should specify the name to be used for JNDI lookups that is consistent with the names provided to the EJB components during deployment in the
AdventNet, Inc.
247
deployment descriptors. A sample property file entry for launching the SNMP server in the application server can be as follows. weblogic.system.startupClass.SnmpEJBServer=com.adventnet.snmp.weblogic.SnmpStarter 3. Start the application server: The user should start the application server. This also starts the SnmpEJBServer factory. Check for error messages during startup. Note: Users should ensure that the required jar files are available in the CLASSPATH of the server. For example for BEA Weblogic on NT, the following command in the startWeblogic.cmd batch file sets up the path to include AdventNetSnmp.jar, AdventNetRMI.jar, AdventNetEJB.jar, AdventNetLogging.jar, a jar file containing SnmpStarter.class. It is assumed that the com.adventnet.snmp.weblogic.SnmpStarter class is available in <AdventNet\SNMPAPI\reference\ejb> directory. If it is in a different directory, include it in the PRE_CLASSPATH. 4. Deploy the EJB component into the application server: The user needs to deploy the EJB components, such as SnmpTargetEJB, SnmpTableEJB, and MibOperationsEJB within the application server before executing the example applications. BEA Weblogic, as well as other application servers, provide a deployment tool with the application server for this purpose. AdventNet provides three jar files namely std_SnmpTargetEJB.jar, std_SnmpTableEJB.jar, and std_MibOperationsEJB.jar in the <AdventNet\SNMPAPI\reference\ejb> directory. These are the jar files required for the deployment tools. Follow the instructions to use the individual deployment tools corresponding to the application server. The jar file std_SnmpTargetEJB.jar contains : SnmpTargetEJB component SnmpTarget interface SnmpTargetHome interface ejb-jar.xml The jar file std_SnmpTableEJB.jar contains : SnmpTableEJB component, SnmpTable interface SnmpTableHome interface ejb-jar.xml The jar file std_MibOperationsEJB.jar contains : MibOperationsEJB component, MibOperations interface MibOperationsHome interface ejb-jar.xml Note: While deploying the EJB jar files, users should ensure that the required jars are available in the CLASSPATH, before the application server's classes of the deployment tool (especially in case of WebLogic). For example for BEA Weblogic on NT, the following CLASSPATH elements should be added to set up the CLASSPATH to include AdventNetSnmp.jar, AdventNetRMI.jar, AdventNetEJB.jar, AdventNetLogging.jar, a jar file containing SnmpStarter.class. If the default JNDI name for the SNMP server is changed, ensure that the JNDI naming convention used for the server instead of SnmpEJBServer is consistent with the convention supplied to the EJB in the SnmpLookupName property.
AdventNet, Inc.
248
5. Test example applications: After the above steps are completed, client applications can communicate with the EJB components to perform SNMP operations. Compile and test the example applications and include the application server's classes in your CLASSPATH.
Standard Setting
1. Copy the following jars from the AdventNet SNMP API package and drop them under <WebLogic HOME>\server\ext directory. AdventNetSnmp.jar AdventNetRMI.jar AdventNetEJB.jar AdventNetLogging.jar A jar file containing SnmpStarter.class (explained later).
2. Edit the startWLS.bat file (at <WebLogic HOME>\server\bin directory) and include the above mentioned AdventNetSNMP jar files in the CLASSPATH environment variable. Note: The AdventNetSNMP jar files should be present before the weblogic.jar in the CLASSPATH.
Deployment Steps
1. Ensure the standard settings are performed. 2. Update the AdventNet SNMP EJB jar file with a valid weblogic-ejb-jar.xml file into the META-INF directory. 3. Save the updated jar file. 4. Drop the above jar file into the <WebLogic HOME>\samples\server\config\examples\applications directory. When the WebLogic Server starts the jar will get deployed automatically.
AdventNet, Inc.
249
Standard Setting
1. Edit the setEnv.bat file (at <WebLogic HOME>\config\mydomain directory) and include the following in the CLASSPATH. AdventNetSnmp.jar AdventNetRMI.jar AdventNetEJB.jar AdventNetLogging.jar Jar file containing SnmpStarter.class 2. Edit the startWebLogic.cmd file and include above-mentioned jar files in the CLASSPATH.
Deployment Steps
1. Ensure the standard settings are performed. 2. Update the AdventNetSNMP EJB jar files with a valid weblogic-ejb-jar.xml file into the META-INF directory. 3. Save the updated jar file. 4. To the above jar file, run weblogic.ejbc to generate the container classes. Usage: java weblogic.ejbc [options] < source jar file > < target directory or jar file > Example: java weblogic.ejbc c:\EJBJars\std_SnmpTarget.jar c:\weblogic\mydomain\applications\SnmpTarget.jar The example command would generate container classes and put them in the SnmpTarget.jar file. This SnmpTarget.jar file is deployed into the WebLogic container. 5. Now deploy the jar containing the generated container classes and other user-defined classes into the container using the following command. Usage:java weblogic.deploy [options] [list|deploy|undeploy|update] password {name} {source} Example: java weblogic.deploy deploy <password> SnmpTargetEJB c:\weblogic\mydomain\applications\SnmpTarget.jar The above command deploys the EJB into the container. Note: The WebLogic server should be running while deploying the EJB.
AdventNet, Inc.
250
Note: If the WebLogic server is already running while doing the changes to the config.xml file, the changes would not take effect. Therefore, shut down the server before making the changes and then restart after the changes are made.
Standard Setting
1. Edit the setEnv.bat file (<WebLogic HOME> directory) and include the following jars in the CLASSPATH variable. AdventNetSnmp.jar AdventNetRMI.jar AdventNetEJB.jar AdventNetLogging.jar Jar file containing SnmpStarter.class 2. Edit the startWebLogic.cmd file and include the above-mentioned jar files in the CLASSPATH.
Deployment Steps
1. Ensure the standard settings are performed. 2. Update the AdventNet SNMP EJB jar file with a valid weblogic-ejb-jar.xml file into the META-INF directory. 3. Save the updated jar file. 4. To the above jar file, run weblogic.ejbc to generate the container classes. Usage: java weblogic.ejbc [options] <source jar file> <target directory or jar file> Example:java weblogic.ejbc c:\EJBJars\std_SnmpTarget.jar c:\ejbExamples\temp\SnmpTarget.jar
AdventNet, Inc.
251
The example command generates container classes and puts them in the SnmpTarget.jar file. This SnmpTarget.jar file is deployed into the WebLogic container. 5. Now deploy the jar containing the generated container classes and other user-defined classes into the container using the following command. Usage: java weblogic.deploy [options] [list|deploy|undeploy|update] password {name} {source} Example: java weblogic.deploy deploy <password> SnmpTargetEJB c:\ejbExamples\temp\SnmpTarget.jar The above command deploys the EJB into the container. Note: The WebLogic server should be running while deploying the EJB.
AdventNet, Inc.
252
Examples
Setting Up the Environment Data Retrieval Examples Data Altering Examples Traps and Inform Examples Table Handling Examples MIB Handling Examples Other Examples
This section details about the various example applications that are bundled with AdventNet SNMP API package and the instructions on setting up the environment to use them.
AdventNet, Inc.
253
This section gives an overview of the usage of the various command line tools and the issues associated with running network management applets.
AdventNet, Inc.
254
Using Applications
Running RMI Examples Running CORBA Examples Running EJB Examples
There are multiple versions of applications, such as snmpget, snmpgetnext, etc. available with this package. You can use them to query information from the SNMP agents. All the applications that are used to query an agent have identical syntax. These examples can also be used as tools to perform some simple SNMP management operations on remote agents. The product distribution includes various example applications in the <examples> directory of the package. applications/ - contains examples that use beans package uiapplications/ - contains examples that use ui package low_level_api_examples/snmpapps/ - contains examples that use snmp2 package low_level_api_examples/mibapps/ - contains examples that use mibs package low_level_api_examples/tcpapps/ - contains examples that use tcp as the underlying protocol sasapps/ - contains examples that use sas package httpapps/ - contains examples that use HTTP tunelling rmiclient/ - contains examples that use rmi package corbaclient/ - contains examples that use corba package ejbclient/ - contains ejb client application examples
Detailed usage instructions on the examples provided in the AdventNet SNMP API package are explained in the subsequent sections. You can use these applications to manage devices and applications easily. As a general rule, all the command line tools gives help information when we type: java <command-name> For example, to get help information on the command snmpgetnext, just type: java snmpgetnext All the example applications can be executed by setting the proper environment variables (setenv.sh or setenv.bat). Note: You must have successfully installed the AdventNet SNMP API product and completed the Installation and Setup procedure. It is very important that you complete the setup procedure before you begin to use the example tools and applications.
AdventNet, Inc.
255
Server Setup
Include the AdventNet SNMP API classes directory or the AdventNetSnmp.jar in your CLASSPATH. Start the RMI registry server and type the following command from a DOS prompt or a UNIX shell.
rmiregistry
Start the RMI SNMP server from the same host as the RMI registry server. Type the following command, after ensuring correct PATH and CLASSPATH settings. java com.adventnet.snmp.rmi.SnmpFactoryImpl All command line examples assume that the client and server are on the same host. If not, use the -SnmpServer SERVER option to specify the RMI server host. The SnmpServer should contain the host:port value. e.g. -SnmpServer localhost:9001. Note: The MIBs path and hostname are relative to the server and not to the client. If the AdventNetSNMP RMI server (i.e. SnmpFactoryImpl) is running on a different host, the examples should use the SnmpServer as follows. java rmiget -SnmpServer SomeHost:9000 localhost 1.1.0 where, 'SomeHost' is the host machine name where the RMI server is running and '9000' is the port at which it is bound to the registry.
Server Setup
Start the CORBA transient name server that comes with the JDK 1.2 and type the following command from the DOS prompt or UNIX shell. tnameserv -ORBInitialPort 1050 This starts the CORBA transient name server at TCP port number 1050. Before starting the CORBA SNMP server, ensure that your PATH and CLASSPATH settings are appropriate so that the java executable and the com.adventnet.snmp.corba.server are accessible. Then start the CORBA SNMP server on the same host which runs the CORBA transient name server by typing the following command. java com.adventnet.snmp.corba.server -ORBInitialPort 1050
AdventNet, Inc.
256
After you start the server, wait till the CORBA SNMP server binds its names with the CORBA transient name server. All command-line syntax examples given in each of the files assume that the client and the server are on the same host. If not, please use the -SnmpServer SERVER option to specify the CORBA server host. Note: The hostname and MIBs path are related to the server and not to the client. After a MIB is loaded on the server, it is available for subsequent client requests. If the AdventNetSNMP CORBA server is running in a different host, the examples should use the 'SnmpServer', 'ORBInitialHost' and 'ORBInitialPort' as follows. java corbaget -SnmpServer <ServerHost> -ORBInitialHost <ORBHost> -ORBInitialPort <ORBPort> localhost 1.1.0 where, '<ServerHost>' is the host machine name where the CORBA server is running, '<ORBHost>' is the host name of transient name server, and '<ORBPort>' is the port on which the transient name server is running.
AdventNet, Inc.
257
Running Applets
Java applets run in web browsers and these browsers often place restrictions on the capabilities of the applets, sometimes for valid security reasons. For example, currently an applet cannot communicate directly with any host in the network, except the web server from which the applet was downloaded. This security restriction does not apply to the applets loaded from CLASSPATH on the local file system on Netscape 3.x, Internet Explorer 3.x and 4.x. However, Netscape 4.x does not allow such applets to connect to the network. Internet Explorer 4.x also places restrictions on connecting through UDP. You cannot run an SNMP applet in Internet Explorer 4.x unless the CAB archive containing the applet is a signed CAB archive because SNMP runs on top of UDP. In short, doing anything but communicating directly back to the web server host through TCP connections is subject to the vagaries of the browser vendors' latest release. However, they are consistent about one thing, i.e., allowing TCP connections back to the server. In this distribution, SAS, allows you to take advantage of this to perform SNMP communication in a uniform way. For applets, the AdventNet SNMP package provides special support to get around the security restriction. AdventNet provides a Java program for the web server called SAS that allows the applet to send and receive SNMP packets from any managed device accessible from the applet host. You need to run this program on your web server if you intend to use the browser without loading the JDK on your local machine and using its class files in your browser. SAS facilitates communication between the applets and any managed device, overcoming the security restrictions placed on the applet. Note: You should have completed the steps mentioned in Installation and Setup on the start_server.bat (Windows) or start_server.sh (Unix) file before you run the applets. The start_server script starts both the WebServer and the SAS. The WebServer is started on port 8282 and the SAS is started on any available port. The SAS port information is written to the file SASPort.html in the specified directory. Let us assume the WebServer and SAS are running on host named hostname. To use the applet in web browser, type the following URL. http://<hostname>:8282/<directory name>/<file name>.html When the applet is loaded in your browser, you can use it to query any SNMP device on the network. SNMP communication through applets can also be done using HTTP. Though TCP/IP connection is more efficient than HTTP, HTTP access is required when we want to communicate to a network with firewall restrictions. The applet support through HTTP in AdventNet API is by means of servlets residing in a web server. HttpSnmpGWServlet is started with the web server. The applet forwards the request to HttpSnmpGWServlet using HTTP. HttpSnmpGWServlet uses the snmp classes to forward and get the response from the remote device and pass it back to the applet using HTTP. Therefore, you have the option of selecting between using TCP/IP and HTTP for connecting between the applet and the server (SAServer in case of TCP/IP and HTTPSnmpGWServlet incase of HTTP). For selecting between these two options, you have to specify the value of the parameter PROTOCOL in the HTML file. For more details, see Applications of SAS API.
AdventNet, Inc.
258
AdventNet, Inc.
259
SNMP GET
The snmpget example is used to query SNMP information in a remote host in which the agent runs. The following command can be used to perform an SNMP query. java snmpget localhost 1.1.0 The above command performs a GET operation on the SNMP agent running on localhost to get the value of the variable 1.1 (sysDescr) and display the results. Depending on whether the localhost has an SNMP agent installed, you get sysDescr or time out message. It takes several seconds for either result. By default, it uses the UDP port 161, SNMP version 1, and the community name public. Other options, such as timeout, retries, setting the debug on, etc. can also be set in the command line. For example we can give the following command for a v2c request in the port (8001) with community name private. java snmpget -v v2 -c private -p 8001 localhost 1.1.0 Note that the given OID 1.1.0 does not start with a dot (.). OIDs not starting with a dot are prefixed by .1.3.6.1.2.1. Therefore, the entire OID of 1.1.0 becomes .1.3.6.1.2.1.1.1.0. We can also give the entire OID for the request. The OID can also be given in the String format instead of the numeric format if we load the corresponding MIB file. For example, java snmpget -m ../../mibs/RFC1213-MIB localhost ysDescr.0 java snmpget -m ../../mibs/RFC1213-MIB localhost .iso.org.dod.internet.mgmt.mib-2.system.sysDescr.0 We can also make multiple OID queries in a single request as follows. java snmpget localhost 1.1.0 1.2.0 1.3.0 To query an SNMPv3 agent running on a system v3agenthost, listening for SNMPv3 requests on port v3port, we need to know the users configured on the agent and their security configuration. Let us assume that the following USM configuration exist for v3agenthost. S.No. 1 2 3 UserName initial initial_a initial_ap SecurityLevel NoAuthNoPriv AuthNoPriv AuthPriv authProtocol none MD5 SHA authPassword none initialPass initialPass privPassword none none initialPass
Let us look at how this SNMPv3 agent can be queried using the snmpget application available with this package. To query the same information with this SNMPv3 agent without using authentication and privacy (NoAuthNoPriv profile), use the following command. java snmpget -v v3 -p v3port -u initial v3agenthost 1.1.0 To query using authentication and no privacy (AuthNoPriv profile), the following command is used. java snmpget -v v3 -p v3port -u initial_a -a MD5 -w initialPass v3agenthost 1.2.0
AdventNet, Inc.
260
To query using authentication and privacy (AuthPriv profile), use the following command. java snmpget -v v3 -p v3port -u initial_ap -a MD5 -w initialPass -s initialPass v3agenthost 1.2.0 One of the common errors that are made during the snmpget request is to query the agent without giving the instance value of the object. To specify an object to an SNMP agent, both the Object ID (which defines the type of object) and the instance (the specific object of the given type) need to be provided. For non-tabular or scalar objects, this is simply an instance of 0 (e.g. sysDescr.0). For example, if we make the following request without giving the instance value, java snmpget localhost 1.1 we get the following error: Request failed or timed out. Error Indication in response: There is no such variable name in this MIB. Errindex: 1 Therefore, we need to make sure that we completely specify the OID plus instance as follows. java snmpget localhost 1.1.0
Source
API Used High-level API Low-level API MIB support API RMI API CORBA API EJB API Available In <examples/applications/snmpget.java> <examples/low_level_api_examples/snmpapps/snmpget.java> <examples/low_level_api_examples/mibapps/snmpget.java> <examples/rmiclient/rmiget.java> <examples/corbaclient/corbaget.java> <examples/ejbclient/ejbget.java>
Usage
The usage of the snmpget is provided below. The "-d" option enables the debug and prints the packet dumps. The "host" and the "OID" arguments are mandatory and the rest are optional. java snmpget [-d] [-v version(v1,v2,v3)] [-c community] [-p port] [-t timeout] [-r retries] [-u user] [-a auth_protocol] [-w auth_password] [-s priv_password] [-i context_id] host OID [OID] ... java ejbget [-EJBServer hostName] [-v version(v1,v2,v3)] [-m MIB_files] [-c community] [-p port] [-t timeout] [-r retries] [-u user] [-a auth_protocol] [-w auth_password] [-s priv_password] [-i contextID] [-n contextName] host OID [OID] ...... java rmiget [-SnmpServer hostName] [-v version(v1,v2,v3)] [-m MIB_files] [-c community] [-p port] [-t timeout] [-r retries] [-u user] [-a auth_protocol] [-w auth_password] [-s priv_password] [-i contextID] [-n contextName] host OID [OID] ... java corbaget [-SnmpServer hostName] [-ORBInitialPort orbPort] [-ORBInitialHost orbHost] [-v version(v1,v2,v3)] [-m MIB_files] [-c community] [-p port] [-t timeout] [-r retries] [-u user] [-a auth_protocol] [-w auth_password] [-s priv_password] [-i context_id] [-n contextName] host OID [OID] ...
AdventNet, Inc.
261
SNMP GETNEXT
The snmpgetnext example is similar to the snmpget example, except that GETNEXT retrieves the value of the next OID in the tree. For example: java snmpgetnext localhost 1.1.0 The above command performs a GETNEXT operation with the SNMP agent running on localhost to get the value of the variable 1.2. (sysObject ID) and display the results. Depending on whether the localhost has an SNMP agent installed, you get the next OID sysObjectId or time out message. It takes several seconds for either result. Note that it does not return the value of 1.1 but 1.2, the OID next to 1.1. All the remaining options such as making multiple OID requests, specifying versions, etc., are applicable to this utility also. Refer SNMP GET for details. Also, providing the instance value as part of the OID is not mandatory. The snmpgetnext always returns the next OID in the MIB tree regardless of whether we specify the particular instance of OID. Therefore, the following command is equally valid. java snmpgetnext localhost 1.1
Source
API Used High-level API Low-level API MIB support API RMI API CORBA API EJB API Available In <examples/applications/snmpgetnext.java> <examples/low_level_api_examples/snmpapps/snmpgetnext.java> <examples/low_level_api_examples/mibapps/snmpgetnext.java> <examples/rmiclient/rmigetnext.java> <examples/corbaclient/corbagetnext.java> <examples/ejbclient/ejbgetnext.java>
Usage
The usage of the snmpgetnext is provided below. The "-d" option enables the debug and prints the packet dumps. The "host" and the "OID" arguments are mandatory and the rest are optional. java snmpgetnext [-d] [-v version(v1,v2,v3)] [-c community] [-p port] [-t timeout] [-r retries] [-u user] [-a auth_protocol] [-w auth_password] [-s priv_password] [-i context_id] host OID [OID] ... java ejbgetnext [-EJBServer hostName] [-v version(v1,v2,v3)] [-m MIB_files] [-c community] [-p port] [-t timeout] [-r retries] [-u user] [-a auth_protocol] [-w auth_password] [-s priv_password] [-i contextID] [-n contextName] host OID [OID] ... java rmigetnext [-SnmpServer hostName] [-v version(v1,v2,v3)] [-m MIB_files] [-c community] [-p port] [-t timeout] [-r retries] [-u user] [-a auth_protocol] [-w auth_password] [-s priv_password] [-i contextID] [-n contextName] host OID [OID] ... java corbagetnext [-SnmpServer hostName] [-ORBInitialPort orbPort] [-ORBInitialHost orbHost] [-v version(v1,v2,v3)] [-m MIB_files] [-c community] [-p port] [-t timeout] [-r retries] [-u user] [-a auth_protocol] [-w auth_password] [-s priv_password] [-i context_id] [-n context_name] host OID [OID] ...
AdventNet, Inc.
262
SNMP GETBULK
The snmpgetbulk performs an SNMP GETBULK operation on a remote agent. The syntax and the command line arguments are similar to the snmpget and the snmpgetnext with two additional parameters specific to GETBULK operation namely Nonrepeaters and Max-repetitions. The GETBULK operation can be used only for v2c and v3 versions. For example, the following command works only if the agent version is v2c or v3. java snmpgetbulk localhost 1.1 The above command performs a GETBULK operation with the SNMP agent running on localhost to get the value of all the variables under the subtree 1.1. and display the results. Depending on whether the localhost has an SNMP agent installed, you get OIDs based on the Max-repetitions value, Nonrepeaters value, and the OID or time out message. All the remaining options such as making multiple OID requests, specifying versions, etc., are applicable to this utility also. Refer SNMP GET for details.
Source
API Used High-level API Low-level API MIB support API RMI API CORBA API EJB API Available In <examples/applications/snmpgetbulk.java> <examples/low_level_api_examples/snmpapps/snmpbulk.java> <examples/low_level_api_examples/mibapps/snmpbulk.java> <examples/rmiclient/rmigetbulk.java> <examples/corbaclient/corbagetbulk.java> <examples/ejbclient/ejbgetbulk.java>
Usage
The usage of the snmpgetbulk is provided below. The "-d" option enables the debug and prints the packet dumps. The "host" and the "OID" arguments are mandatory and the rest are optional. java snmpgetbulk [-d] [-v version(v2,v3)] [-c community] [-p port] [-t timeout] [-r retries] [-nr nonrepeaters] [-mr max-repetitions] [-u user] [-a auth_protocol] [-w auth_password] [-s priv_password] [-i context_id] host OID [OID] ... java ejbgetbulk[-EJBServer hostName] [-v version(v2,v3)] [-m MIB_files] [-c community] [-p port] [-t timeout] [-r retries] [-nr non-repeaters] [-mr max-repetitions] [-u user] [-a auth_protocol] [-w auth_password] [-s priv_password] [-i contextID] [-n contextName] host OID [OID] ... java rmigetbulk [-SnmpServer hostName] [-v version(v1,v2,v3)] [-m MIB_files] [-c community] [-p port] [-t timeout] [-r retries] [-nr non-repeaters] [-mr max-repetitions] [-u user] [-a auth_protocol] [-w auth_password] [-s priv_password][-i contextID] [-n contextName] host OID [OID] ... java corbagetbulk [-SnmpServer hostName] [-ORBInitialPort orbPort] [-ORBInitialHost orbHost] [-v version(v2,v3)] [-m MIB_files] [-c community] [-p port] [-t timeout] [-r retries] [-nr non-repeaters] [-mr max-repetitions] [-u user] [-a auth_protocol] [-w auth_password] [-s priv_password] [-i context_id] [-n contextName] host OID [OID] ...
AdventNet, Inc.
263
SNMP Walk
The snmpwalk example does a walk on one or more OIDs by performing a series of GETNEXTs and stops inside the range of the OID. For example: >java snmpwalk localhost 1 java snmpwalk -m ../../mibs/RFC1213-MIB localhost system The above command displays all the results for the system group in the localhost where the agent runs. It stops within the range of system group OID. Depending on whether the localhost has an SNMP agent installed, you get all the OIDs belonging to the "system" tree or time out message. It takes several seconds for either result. All the remaining options such as setting retries values, specifying versions, etc., are applicable to this utility also. Refer SNMP GET for details.
Source
API Used High-level API Low-level API MIB support API RMI API EJB API Available In <examples/applications/snmpwalk.java> <examples/low_level_api_examples/snmpapps/snmpwalk.java> <examples/low_level_api_examples/mibapps/snmpwalk.java> <examples/rmiclient/rmiwalk.java> <examples/ejbclient/ejbwalk.java>
Usage
The usage of the snmpwalk is provided below. The "-d" option enables the debug and prints the packet dumps. The "host" and the "OID" arguments are mandatory and the rest are optional. java snmpwalk [-v version(v1,v2,v3)] [-m MIB_files] [-c community] [-p port] [-t timeout] [-r retries] [-u user] [-a auth_protocol] [-w auth_password] [-s priv_password] [-n contextName] [-i contextID] [-d debug] host OID java ejbwalk [-EJBServer hostName] [-v version(v1,v2,v3)] [-m MIB_files] [-c community] [-p port] [-t timeout] [-r retries] [-u user] [-a auth_protocol] [-w auth_password] [-s priv_password] [-i contextID] [-n contextName] host OID [OID] ... java rmiwalk [-SnmpServer hostName] [-v version(v1,v2,v3)] [-m MIB_files] [-c community] [-p port] [-t timeout] [-r retries] [-u user] [-a auth_protocol] [-w auth_password] [-s priv_password] [-i contextID] [-n contextName] host OID [OID] ...
AdventNet, Inc.
264
AdventNet, Inc.
265
SNMP SET
The snmpset example allows the management application or the manager to SET the value of an attribute of a managed object in the agent. To perform the SET operation in a remote host in which the agent resides, we need to specify the OID, the data type and the value to be set. In this example, the datatype is taken from the MIB file. For example: java snmpset -m ../../mibs/RFC1213-MIB localhost 1.5.0 testing The above command performs a SET operation with the SNMP agent running on localhost to set the value of the variable 1.5. (sysName) to "testing". The above command results in an SNMP SET operation to the localhost on the sysContact OID. Depending on whether the localhost has an SNMP agent installed, you get sysContact or time out message. It takes several seconds for either result. To check the new value, you can perform an snmpget and see the new value being retrieved. To perform the SET operation, loading the MIB file is a must because the type of the object is retrieved from the MIB file. If the MIB file is not available, we must give the type of the OID. We have provided another example for performing the SET operation without loading the MIB file. We need to have write permission to set the value for the managed object. Otherwise, the following error occurs (if the version is v1). Request failed or timed out. Error Indication in response: There is no such variable name in this MIB. Errindex: 1 If the version is v2c, the following error message appears. Request failed or timed out. Error Indication in response: A no creation error occurred. Errindex: 1
Source
API Used High-level API Low-level API MIB support API RMI API CORBA API EJB API Available In <examples/applications/snmpset.java> <examples/low_level_api_examples/snmpapps/snmpset.java> <examples/low_level_api_examples/mibapps/snmpset.java> <examples/rmiclient/rmiset.java> <examples/corbaclient/corbaset.java> <examples/ejbclient/ejbset.java>
Usage
The usage of the snmpset utility is provided below. The "-d" option enables the debug and prints the packet dumps. The "mib files" "host" "OID" and the "value" arguments are mandatory and the rest are optional. java snmpset [-v version(v1,v2)] [-c community] [-p port] [-t timeout] [-r retries] [-u user] [-a auth_protocol] [-w auth_password] [-s priv_password] [-d debug] -m MIB_files host OID value [OID value] ... java ejbset [-EJBServer hostName] [-v version(v1,v2,v3)] [-c community] [-p port] [-t timeout] [-r retries] [-u user] [-a auth_protocol] [-w auth_password] [-s priv_password] [-i contextID] [-n contextName] -m MIB_files host OID value ...
AdventNet, Inc.
266
java rmiset [-SnmpServer hostName] [-v version(v1,v2,v3)] [-c community] [-p port] [-t timeout] [-r retries] [-u user] [-a auth_protocol] [-w auth_password] [-s priv_password] [-i contextID] [-n contextName] -m MIB_files host OID value ... java corbaset [-SnmpServer hostName] [-ORBInitialPort orbPort] [-ORBInitialHost orbHost] [-v version(v1,v2,v3)] [-c community] [-p port] [-t timeout] [-r retries] [-u user] [-a auth_protocol] [-w auth_password] [-s priv_password] [-i context_id] [-n context_name] -m MIB_files host OID value
AdventNet, Inc.
267
Usage
The usage of the snmpset_without_mib utility is provided here below. The "-d" option enables the debug and prints the packet dumps. The "host", "OID", any one among the type and the "value" arguments are mandatory and the rest are optional. java snmpset_without_mib [-v version(v1,v2)] [-c community] [-p port] [-t timeout] [-r retries] [-u user] [a auth_protocol] [-w auth_password] [-s priv_password] [-d debug] [-m MIB_files] host OID {INTEGER | STRING | GAUGE | TIMETICKS | OPAQUE | IPADDRESS | COUNTER | OID } value [OID type value] ...
Example Command
java snmpset_without_mib 10.3.2.120 sysLocation.0 STRING paradise Refer the source code of the snmpset_without_mib example in <examples/applications/snmpset_without_mib.java> for more information.
AdventNet, Inc.
268
Traps are unsolicited messages sent by the agent to the management applications to report the conditions of the managed node. SNMP v2c/v3 traps are also called as notifications. SNMP v2 notification is different from the v1 traps with much simplification. The inform requests can be sent from a manager to another manager. A trap receiver program in the manager station can receive and display inform messages. By default, the inform requests are sent to the port 162 of the manager station.
AdventNet, Inc.
269
Trap Receiver
Traps are unsolicited messages sent by the agent to the management applications to report the conditions of the managed node. The trapreceiver example can be used to receive the traps sent by the agents. For example: java trapreceiver The above command waits for the trap in the port 162, the default port for receiving traps, and prints the received traps. In some operating systems, such as Unix, some ports are accessible only for users with root privileges. The following error occurs, if the port is not accessible. Error: com.adventnet.snmp.snmp2.SnmpException: java.net.BindException: Permission denied In such cases, you can specify the port in which the trap can be received as follows. java trapreceiver -p 8001 Here, the traps are received in the port 8001. For example, the following v1 trap: java sendtrap -p 8001 -m ../../mibs/RFC1213-MIB remotehost 1.2.0 localhost 0 6 1000 1.5.0 testing gives the following output in the trapreceiver demon. Got a trap from: xx.xx.xx.xx SNMP Trap PDU SNMP Version: Version 1 Remote Host: xx.xx.xx.xx Remote Port: 1430 Community: public Request ID: 0 Timeout: 0 Retries: 0 Enterprise: .1.3.6.1.2.1.1.2.0 Trap Type: 0 Specific Type: 6 UpTime: 1000 Error Status: no error SNMP PDU Variable Bindings: Object ID: .1.3.6.1.2.1.1.5.0 STRING: testing The output of the trapreceiver is different if we send a v2c/v3 trap. java sendv2trap -p 8001 -m ../../mibs/RFC1213-MIB remotehost 5000 1.2.0 1.5.0 test Output of the trapreceiver is: Got a trap from: 192.168.1.40 SNMP V2 Trap PDU SNMP Version: Version 2C Remote Host: 192.168.1.40 Remote Port: 1436
AdventNet, Inc.
270
Community: public Request ID: 2 Timeout: 0 Retries: 0 Error Status: no error SNMP PDU Variable Bindings: Object ID: .1.3.6.1.2.1.1.3.0 TIMETICKS: 0 hours, 0 minutes, 50 seconds. Object ID: .1.3.6.1.6.3.1.1.4.1.0 OBJID: .1.3.6.1.2.1.1.2.0 Object ID: .1.3.6.1.2.1.1.5.0 STRING: test
Source
API Used High-level API Low-level API MIB Support API RMI API CORBA API Available in <examples/applications/trapreceiver.java> <examples/low_level_api_examples/snmpapps/snmptrapd.java> <examples/low_level_api_examples/mibapps/snmptrapd.java> <examples/rmiclient/rmitrapreceiver.java> <examples/corbaclient/corbatrapreceiver.java>
Usage
The usage of the trapreceiver utility is provided below. java snmptrapd [-v version(v1,v2)] [-m MIB_files] [-c community] [-p port] java rmitrapreceiver [-SnmpServer hostname] [-m MIB_files] [-c community] [-p port] [-u user] [-e engineID] [-a authProtocol] [-w auth_password] [-s priv_password]
AdventNet, Inc.
271
Send Notifications
Traps are unsolicited messages sent by the agent to the management stations to report the conditions of the managed node. The sendv2trap example can be used to send v2c and v3 traps. SNMP v2c/v3 traps are also called as notifications. SNMP v2 notification is different from the v1 traps with much simplification. To send the v2c/v3 notification, you need to provide the following values. remoteHost - the manager station to which the trap message is sent. timeticks - the time elapsed between the last initialization of the network and the generation of the trap. trapOID - the trap OID. MIB file, OID, and value - values for building the varbinds.
Trap messages not containing any varbinds do not need OID and value. The following commands generate a simple v2c/v3 notification. java sendv2trap -m ../../mibs/RFC1213-MIB remotehost 5000 1.5.0 java sendv2trap -p 8001 -m ../../mibs/RFC1213-MIB remotehost 5000 1.2.0 1.5.0 test The above command sends a trap to the manager station in the remotehost. A trap receiver program in the manager station can receive and display the traps. By default, the traps are sent to the port 162 of the manager station.
Source
API Used High-evel API Low-level API MIB Support API Available in <examples/applications/sendv2trap.java> <examples/low_level_api_examples/snmpapps/snmpv2ctrap.java> <examples/low_level_api_examples/mibapps/snmpv2ctrap.java>
Usage
The usage of the sendv2trap utility is provided below. The "MIB_files", "host", "TimeTicksValue", and "trapOID" arguments are mandatory and the rest are optional. Usage: java sendv2trap [-d Debug][-v version(v2,v3)] [-c community] [-p port] [-u user] [-a auth_protocol] [-w auth_password] [-s priv_password] [-i contextName] -m MIB_file host TimeTicksvalue trapOID [OID value] ... Usage: java snmpv2ctrap [-d Debug][-v version(v2,v3)] [-c community] [-p port] [-u user] [-a auth_protocol] [-w auth_password] [-s priv_password] [-i contextName] -m MIB_file host TimeTicksvalue trapOID [OID value] ... java snmpv3trap [-d] [-p port] [-e engineID(0x....)] [-a auth_protocol] [-w auth_password] [-s priv_password] [-i context_id] userName host TimeTicksvalue OIDvalue [OID {INTEGER | STRING | GAUGE | TIMETICKS | OPAQUE | IPADDRESS | COUNTER | COUNTER64 | UNSIGNED32} value] ...
Options
[-d] - Debug output. By default, off. -p] port - Remote port number. By default, 162.
AdventNet, Inc.
272
[-e] engineid - Engine ID. [-a] authprotocol - authProtocol (MD5/SHA). Mandatory if authPassword is specified. [-w] authpassword - The authentication password. [-s] privpassword - The privacy protocol password. Must be accomspanied with authpassword and authprotocol fields. [-n] contextname - The contextName to be used for the v3 PDU. [-i] contextid - The contextID to be used for the v3 PDU. username - The v3 principal/userName. Mandatory. timeticks - The value of object sysUpTime when the event occurred. Mandatory. OID-value - Object Identifier. Mandatory. host - Remote host (agent). Mandatory. OID - Object Identifier. Mandatory. value - The object instance value to be set. Mandatory.
AdventNet, Inc.
273
The following commands generate a simple v2c/v3 inform request. java sendinform -m ../../mibs/RFC1213-MIB remotehost 5000 1.5.0 java sendinform -p 8001 -m ../../mibs/RFC1213-MIB remotehost 5000 1.2.0 1.5.0 test The above command sends an inform message to the manager application in the remote host. A trap receiver program in the manager station can receive and display the inform message. By default, the inform requests are sent to the port 162 of the manager station.
Source
Refer the source code for the sendinform example present in <examples/applications/sendinform.java> for more information.
Usage
The usage of the sendinform utility is provided below. The "MIB_files", "host", "TimeTicksValue", and "trapOID" arguments are mandatory and the rest are optional. Usage: java sendinform [-d Debug][-v version(v2,v3)] [-c community] [-p port] [-u user] [-a auth_protocol] [-w auth_password] [-s priv_password] [-i contextName] -m MIB_file host TimeTicksvalue trapOID [OID value] ...
AdventNet, Inc.
274
Source
Refer the source code for the snmpv2cinformreq example present in <examples/low_level_api_examples/snmpapps/snmp2cinformreq.java> for more information.
Usage
java snmpv2cinformreq [options] hostname timeTicks snmpTrapOid-value [OID type value] java snmpv2cinformreq [-d] [-c community] [-p port] host TimeTicksvalue OIDvalue [OID {INTEGER | STRING | GAUGE | TIMETICKS | OPAQUE | IPADDRESS | COUNTER | COUNTER64 | UNSIGNED32} value] ...
Options
[-d] - Debug output. By default, off. [-c] community - Community string. By default "public". [-p] port - Remote port number. By default, 162. host - Remote host (agent). Mandatory. timeticks - The value of object sysUpTime when the event occurred. Mandatory. OID-value - Object Identifier. Mandatory. OID - Multiple Object Identifiers with values. type - Type of the object. value - The object instance value to be set.
AdventNet, Inc.
275
Source
Refer the source code for the snmpv2cinformreqd example present in <examples/low_level_api_examples/snmpapps/snmpv2cinformreqd.java> for more information.
Usage
java snmpv2cinformreqd [options] java snmpv2cinformreqd [-d] [-p port][-c community]
Options
[-d] - Debug output. By default, off. -p] port - Remote port number. By default, 162. [-c] community - Community string. By default, "public".
Example Command
java snmpv2cinformreqd -p 162 -c public
AdventNet, Inc.
276
An SNMP table can be defined as an ordered collection of objects consisting of zero or more rows. Each row may contain one or more objects. Each object in a table is identified using the table index. A table can have a single index or multiple indices. This section explains some of the examples related to SNMP tables.
AdventNet, Inc.
277
The gettable and the getSnmpTable examples can be used to retrieve the SNMP tables. Both the examples need the MIB file, with the requested table loaded. The output of the table is in a columnar format.
Source
API Used High-level API RMI API CORBA API EJB API Available In <examples/applications/gettable.java> <examples/applications/getSnmpTable.java> <examples/rmiclient/rmitable.java> <examples/corbaclient/corbatable.java> <examples/ejbclient/ejbtable.java>
High-Level API
The following commands retrieve and display the tcpConnTable from the localhost in which the agent runs. java gettable localhost tcpConnTable ../../mibs/RFC1213-MIB java getSnmpTable localhost tcpConnTable ../../mibs/RFC1213-MIB By default, it uses the UDP port 161, SNMP v1, and the community name as public. Other options, such as timeout, retries, setting debug on, etc. can also be set in the command line. You need to give the proper OID of the table as an argument. If you give a non-table OID as the argument, the request fails and the following error is displayed. Not a table. No columns: oid The gettable example uses the SnmpTarget bean for fetching the table while the getSnmptable uses the SnmpTable bean.
Usage
The usage of the gettable and the getSnmpTable utilities are provided below. The "-d" option enables the debug and prints the packet dumps. The "host" "tableOID" and the "MIB_files" arguments are mandatory and the rest are optional. java gettable [-v version(v1,v2,v3)] [-c community] [-p port] [-t timeout] [-r retries] [-u user] [-a auth_protocol] [-w auth_password] [-s priv_password] [-n contextName] [-i contextID] [-d debug] host tableOID MIB_files
AdventNet, Inc.
278
java getSnmpTable [-v version(v1,v2,v3)] [-c community] [-p port] [-t timeout] [-r retries] [-u user] [-a auth_protocol] [-w auth_password] [-s priv_password] [-n contextname] [-i contextID] [-d debug] host tableOID MIB_files
RMI API
The rmitable example can be used to retrieve SNMP tables. The table OID can be given in the String format or in the numeric format. If the OID is in String format, you need to load the corresponding MIB file also. For example, the following commands retrieve and display the ifTable from the localhost in which the agent runs. java rmitable localhost .1.3.6.1.2.1.2.2 or java rmitable localhost ifTable -m ../../mibs/rfc1213-MIB You need to give the proper table OID of the table as an argument. If you give a non-table OID as the argument, the request fails and the following error is displayed. Error : MIB node unavailable for OID
Usage
The usage of the rmitable is provided below. The "host" and "tableOID" arguments are mandatory and the rest are optional. java rmitable [-SnmpServer hostName] [-v version(v1,v2,v3)] [-m MIB_files] [-c community] [p port] [-t timeout] [-r retries] [-u user] [-a auth_protocol] [-w auth_password] [-s priv_password] [-i contextID] [-n contextName] host tableOID ... The rmitable example gets and prints an SNMP Table. It uses the RMI package and the high-level API.
CORBA API
The corbatable example can be used to retrieve the SNMP tables. The table OID can be given in the String format or in the numeric format. If the OID is in String format, we need to load the corresponding MIB file also. For example, the following commands retrieve and display the ifTable from the localhost in which the agent runs. java corbatable localhost .1.3.6.1.2.1.2.2 or java corbatable localhost ifTable -m ../../mibs/rfc1213-MIB
Usage
The usage of the corbatable is provided below. The "host" and the "tableOID" arguments are mandatory and the rest are optional. java corbatable [-SnmpServer hostName] [-ORBInitialPort orbPort] [-ORBInitialHost orbHost] [-v version(v1,v2,v3)] [-mMIB_files] [-c community] [-p port] [-t timeout] [-r retries] [-u user] [-a auth_protocol] [-w auth_password] [-s priv_password] [-i context_id] [-n context_name] host tableOID .. The corbatable example explains how to write an application to perform the table operation using the corba package.
AdventNet, Inc.
279
EJB API
The ejbtable is an application illustrating how to perform an SNMP table-retrieval operation using SnmpTargetEJB. Run the example application from the host where the application server is running as follows. java ejbtable localhost -m mibs\RFC1213-MIB localhost .1.3.6.2.1.2.2
Usage
ejbtable [-EJBServer hostName] [-v version(v1,v2,v3)] [-m MIB_files] [-c community] [-p port] [-t timeout] [-r retries] [-u user] [-a auth_protocol] [-w auth_password] [-s priv_password] [-i contextID] [-n contextName] host OID [OID] ... The above command results in an SNMP table-retrieval operation on the ifTable OID. If the localhost has an SNMP agent installed, you get a response with the values for all the columnar OIDs of ifTable or a time out message. It takes several seconds for either result. Note: Client applications should ensure that the mibs directory is placed under the application server and refer to it with respect to the application server while running client applications. To run the ejbtable application from another host where the application server runs, you can use the following command. java ejbtable localhost -EJBServer SERVER -m mibs\RFC1213-MIB localhost .1.3.6.2.1.2.2 It is assumed that the application server runs on a machine SERVER and you want to retrieve the table on the server itself. The argument "localhost" specifies that the table is retrieved on the "localhost" as seen by the application server.
AdventNet, Inc.
280
Retrieve Table - UI
The AdventNet SNMP API provides the following components which can be used to build UI applications for retrieving tables. SnmpTableModel TableBean SnmpTablePanel
Example I
The example swingtable displays an SNMP MIB Table in a JFC JTable component. This example uses the SnmpTableModel bean with the JFC table component to view any SNMP table for which the MIB file is available. The following command can be used to get the tcpConnTable from the localhost in which the agent runs. java swingtable localhost tcpConnTable ../../mibs/RFC1213-MIB By default, it uses the UDP port 161, SNMP v1, and the community name as public. Other options, such as timeout, retries, setting debug on, etc. can also be set in the command line. The screen shot of this example is given below.
Refer the source code for the swingtable example present in <examples/uiapplications/swingtable.java> for more information. The usage of the swingtable is provided below. The "host" "tableOID" and the "MIB_file" arguments are mandatory and the rest are optional. java swingtable [-v version(v1/v2/v3)] [-c community] [-p port] [-r retries] [-t timeout] [-u userName] [-a authProtocol] [-w authPassword] [-s privPassword] [-n contextname] [-i contextID] host tableOID MIB_file
AdventNet, Inc.
281
Example II
The example tableBeanDemo illustrates the use of the TableBean for displaying the SNMP tables. The TableBean component combines the JFC Table with the SnmpTable and provides a list of enumerated integers to perform set operations. The syntax and the usage are similar to the swingtable example as shown in the following command. java tableBeanDemo localhost tcpConnTable ../../mibs/RFC1213-MIB The screen shot of tableBeanDemo example is given below.
Refer the source code for the tableBeanDemo example present in <examples/uiapplications/tableBeanDemo.java> for more information. The usage of the tableBeanDemo is provided below. The "host" "tableOID" and the "MIB_file" arguments are mandatory and the rest are optional. java tableBeanDemo [-v version(v1/v2/v3)] [-c community] [-p port] [-r retries] [-t timeout] [-u userName] [-a authProtocol] [-w authPassword] [-s privPassword] [-n contextname] [-i contextID] host tableOID MIB_file
Example III
The largetable example illustrates the use of SnmpTablePanel to display large tables. It displays an SNMP MIB Table in a JFC JTable component and handles tables with many column by allowing the break up of data into pages. Here we can select which page to be viewed. The syntax and the usage are similar to the swingtable and the largetable examples as shown in the following command. java largetable localhost ifTable ../../mibs/RFC1213-MIB
AdventNet, Inc.
282
Refer the source code for the largetable example present in <examples/uiapplications/largetable.java> for more information. The usage of the largetable is provided here below. The "host" "tableOID" and the "MIB_file" arguments are mandatory and the rest are optional. java largetable [-v version(v1/v2/v3)] [-c community] [-p port] [-r retries] [-t timeout] [-u userName] [-a authProtocol] [-w authPassword] [-s privPassword] [-n contextname] [-i contextID] host tableOID MIB_file
Example IV
The tableSettingsDemoAppn is another example on the usage of the TableBean for displaying the tables. This example includes set bean properties, such as hostname during run time. The following command invokes the application. java tableSettingsDemoAppn ../../mibs/RFC1213-MIB tcpConnTable
AdventNet, Inc.
283
When the "Get Agent Data" is clicked, the data from the localhost is retrieved by default. Click the "Password" to set different agent host name. Refer the source code for the tableSettingsDemoAppn example present in <examples/uiapplications/tableSettingsDemoAppn.java> for more information. The usage of the tableSettingsDemoAppn is given below. The "MIB_files" and the "oid" (table OID) are mandatory and the rest are optional. java tableSettingsDemoAppn MIB_files [-c community] oid
Example V
This is the applet example to show the usage of the TableBean component. The usage is similar to the tableSettingsDemoAppn example and the applet can be viewed by executing the following command. appletviewer tableSettingsDemo.html
AdventNet, Inc.
284
Refer the source code for the tableSettingsDemo example present in <examples/uiapplications/tableSettingsDemo.java> for more information.
AdventNet, Inc.
285
Walk Indexes
The walk_indexes is an example of SNMP walk application for a table column object where the index values are printed separately. This is a useful example on extracting information from instance values.
Source
Refer the source code for the walk_indexes example present in <examples/applications/walk_indexes.java> for more information.
Usage
The usage of the walk_indexes is provided below. The "-d" option enables the debug and prints the packet dumps. The "host" and the "OID" arguments are mandatory and the rest are optional. java walk_indexes [-v version(v1,v2,v3)] [-m MIB_files] [-c community] [-p port] [-t timeout] [-r retries] [u user] [-a auth_protocol] [-w auth_password] [-s priv_password] [-n contextName] [-i contextID] [-d debug] host OID
Example Command
java walk_indexes -m "../../mibs/RFC1213-mib" 10.3.2.120 tcpConnLocalAdress java walk_indexes -v v3 -u initial -w initialPass -a MD5 -m "../../mibs/RFC1213-mib" 10.3.2.120 tcpConnLocalPort
AdventNet, Inc.
286
Get By Index
The snmpget_by_index is an example of an SNMP GET application for an object where the index values can be specified more easily. This example application gets an SNMP table column instance by specifying the column name and values of one or more indices.
Source
Refer the source code for the snmp_get_by_index example present in <examples/applications/snmp_get_by_index.java> for more information.
Usage
The usage of the snmpget_by_index is provided below. The "-d" option enables the debug and prints the packet dumps. The "host" "OID" and the "Index" arguments are mandatory and the rest are optional. java snmpget_by_index [-v version(v1,v2,v3)] [-m MIB_files] [-c community] [-p port] [-t timeout] [-r retries] [-u user] [-a auth_protocol] [-w auth_password] [-s priv_password] [-n contextName] [-i contextID] [-d debug] host OID index [index] ...
Example Command
java snmpget_by_index -m "../../mibs/RFC1213-mib" 10.3.2.120 atIfIndex 2 128.253.154.1 java snmpget_by_index -v v3 -u initial -w initialPass -a MD5 -m "../../mibs/RFC1213-mib" 10.3.2.120 atPhysAddrress 2 128.253.154.1 java snmpget_by_index -v v3 -u initial -w initialPass -a MD5 -m "../../mibs/RFC1213-mib" 10.3.2.120 ifDescr 2
AdventNet, Inc.
287
Source
Refer the source code of the setTableValue example present in span style="font-style: italic;"><examples/applications/setTableValue.java> for more information.
Usage
The usage of the setTableValue example is provided below. The "-d" option enables the debug and prints the packet dumps. The "host", "tableOID", "MIB_files", "row index" and the "columnIndex" arguments are mandatory and the rest are optional. setTableValue [-v version(v1,v2,v3)] [-c community] [ -p port] [-t timeout] [-r retries] [-u user] [-a auth_protocol(MD5/SHA)] [-w auth_password ] [-s priv_password] [-n contextname] [-i contextID] [-d debug] host tableOID MIB_files rowIndex columnIndex
Example Command
java setTableValue localhost ../../mibs/agent-sample-mib.txt forwardingTable value 0 1
AdventNet, Inc.
288
Source
Refer the source code of the encodeTableIndex example present in <examples/applications/encodeTableIndex.java> for more information.
Usage
The usage of the encodeTableIndex example is provided below. encodeTableIndex tableOID MIB-File index [indices..]
Example Command
java encodeTableIndex atTable ../../mibs/RFC1213-MIB 1 192.168.1.45
AdventNet, Inc.
289
Get Column
The getColumn example is used for retrieving the column value from an SNMP table.
Source
Refer the source code for the getColumn example present in <examples/applications/getColumn.java> for more information.
Usage
The usage of the getColumn example is provided below. The "-d" option enables the debug and prints the packet dumps. The "host" "MIB_files" and the "columnName" arguments are mandatory and the rest are optional. getColumn [-v version(v1,v2,v3)] [-c community] [ -p port] [-t timeout] [-r retries] [-u user] [-a auth_protocol(MD5/SHA)] [-w auth_password ] [-s priv_password] [-n contextname] [-i contextID] [-d debug] host MIB_files columnName
Example Command
java getColumn "../../mibs/RFC1213-mib" 10.3.2.120 ifType java getColumn -v v3 -u initial -w initialPass -a MD5 "../../mibs/RFC1213-mib" 10.3.2.120 ifType
AdventNet, Inc.
290
Get Row
The getRow example is used for retrieving the row value from the SNMP table.
Source
Refer the source code for the getRowexample present in <examples/applications/getRow.java> for more information.
Usage
The usage of the getRow example is provided below. The "-d" option enables the debug and prints the packet dumps. The "host", "tableOID", "MIB_files" and the "rowIndex" arguments are mandatory and the rest are optional. getRow [-v version(v1,v2,v3)] [-c community] [ -p port] [-t timeout] [-r retries] [-u user] [-a auth_protocol(MD5/SHA)] [-w auth_password] [-s priv_password] [-n contextname] [-i contextID] [-d debug] host tableOID MIB_files rowIndex
Example Command
java getRow localhost if Table ../../mibs/RFC1213-mib 1 java getRow -v v3 -u initial -w initialPass -a MD5 localhost if Table ../../mibs/RFC1213-mib 1
AdventNet, Inc.
291
Source
Refer the source code for the getTableInfo example present in <examples/applications/getTableInfo.java> for more information.
Usage
The usage of the getTableInfo example is provided below. getTableInfo ColumnOID MIB_FILE
Example Command
java getTableInfo ifType ../../mibs/RFC1213-MIB
SNMP CORBA
This is a sample GUI application to show the usage of the CORBA API. This example uses the SnmpTarget interface for GET, GETNEXT, GETBULK, and SET and a supplementary class CorbaTableUi with SnmpTable interface for retrieving the table values. The application supports all the three versions of SNMP. This is a user-friendly application and can be viewed by executing the following command. java CorbaDemo The screenshot of this applet example is given below.
AdventNet, Inc.
292
Source
Refer the source code for the CorbaDemo example present in <examples/corbaclient/CorbaDemo.java> for more information.
Usage
The usage of the CorbaDemo is provided below. java CorbaDemo [-ORBInitialPort orbPort] [-ORBInitialHost orbHost] Note: The 'mib path' and 'host' are relative to the server. If the AdventNetSNMP CORBA server runs in a different host, the examples should use the '-ORBInitialHost' and '-ORBInitialPort' as follows. java CorbaDemo -ORBInitialHost <ORBHost> -ORBInitialPort <ORBPort> where '<ORBHost>' is the host name of transient name server '<ORBPort>' is the port on which transient name server is running. The MIB is loaded only on clicking the 'Load MIBs' button. By default, the MIB path is visible but not loaded
AdventNet, Inc.
293
AdventNet, Inc.
294
Source
Refer the source code for the ejbNodeDetails example present in <examples/ejbclient/ejbNodeDetails.java> for more information.
AdventNet, Inc.
295
Source
Refer the source code for the ejbLeafDetails example present in <examples/ejbclient/ejbLeafDetails.java> for more information.
AdventNet, Inc.
296
Source
Refer the source code for the mibTreeDemo example present in <examples/uiapplications/mibTreeDemo.java> for more information.
Usage
java mibTreeDemo -m[mibs]
AdventNet, Inc.
297
Other Examples
Request Server Demo RMI Request Server Demo SNMP Poller Demo RMI Applet Demo Property Settings Demo Line Graph Demo
AdventNet, Inc.
298
Clicking the "Get Agent Data" button gets the value of the variable sysDescr.0 from the agent running in the local host. All the parameters, such as hostname, OID, etc. are set in the HTML file. The HTML file can be edited to put the correct parameters. The HTML file contains the following parameters which can be changed according to the user preferences. param name="MIBS" value="../../mibs/RFC1213-MIB" param name="HOSTNAME" value="localhost" param name="COMMUNITY" value="public" param name="OID" value="sysDescr.0" param name="SNMP_PORT" value="161" param name="SNMP_VERSION" value="0" Following are the steps to view the applet in the web browser. Copy the requestServerDemo*.class to the classes directory. Run the start_server.sh/bat file to start the Web server and SAS. The Web server is started in the port 8282 and SAS in any random port. Load the HTML file as follows to query the agent data.
http://localhost:8282/applications/requestServerDemo.html
Source
Refer the source code for the requestServerDemo example present in <examples/applications/requestServerDemo.java> for more information.
AdventNet, Inc.
299
Clicking the "Get Result" button gets the value of the variable set in the OID textfield. By default, it gets sysUpTime.0 from the agent running in the local host. All the parameters, such as hostname, OID, etc. are set in the HTML file. The HTML file can be edited to put the correct parameters. The HTML file contains the following parameters which can be changed according to the user preferences. <applet code=rmiRequestServerDemo.class width=600 height=200> <param name="MIBS" value="../../mibs/RFC1213-MIB"> <param name="RMISERVER" value=""> <param name="HOSTNAME" value="localhost"> <param name="COMMUNITY" value="public"> <param name="OID" value="sysUpTime.0"> <param name="SNMP_VERSION" value="0"> <param name="SNMP_PORT" value="161"> </applet> Note: The 'mib path' and 'host' are relative to the server. If the AdventNetSNMP RMI server (SnmpFactoryImpl) runs in a different host, set the value for the RMISERVER' in the HTML file as follows. <param name="RMISERVER" value="SomeHost:9000"> where 'SomeHost' is the host machine name in which the RMI server runs '9000' is the port at which it is bound to the registry.
AdventNet, Inc.
300
Source
Refer the source code for the rmiRequestServerDemo example present in <examples/rmiclient/rmiRequestServerDemo.java> for more information.
AdventNet, Inc.
301
SnmpPoller Demo I
This is a simple applet example to show the usage of the SnmpPoller bean. The SnmpPoller Demo I application is used for doing automatic polling of SNMP variables. The applet can be viewed by executing the following command. appletviewer -J-Xbootclasspath:applications.jar; ..\..\jars\AdventNetLogging.jar; ..\..\jars\AdventNetSnmp.jar;<JDK_HOME>\jre\lib\rt.jar snmpPollerDemo.html The screenshot of this applet example is given below.
By default, it polls the sysUpTime value. A button is provided to toggle between start and stop polling. All the parameters, such as hostname, OID, etc. are set in the HTML file. The HTML file can be edited. The following parameters in the HTML file can be changed according to the user preferences. param param param param param param name="MIBS" value = "../../mibs/RFC1213-MIB" name="HOSTNAME" value = "localhost" name="COMMUNITY" value = "public" name="OID" value = "sysUpTime.0" name="SNMP_PORT" value = "161" name="SNMP_VERSION" value = "0"
Following are the steps to view the applet in the web browser. Copy the snmpPollerDemo*.class to the classes directory. Run the start_server.sh/bat file to start the Web server and SAS. The Web server is started in the port 8282 and SAS in any random port. Load the HTML file as follows to start polling.
http://localhost:8282/applications/snmpPollerDemo.html
Source
Refer the source code for the snmpPollerDemo example present in <examples/applications/snmpPollerDemo.java> for more information.
AdventNet, Inc.
302
SnmpPoller Demo II
SnmpPoller Demo II is similar to Demo I, the only difference being the addition of Property Settings bean. The screenshot of this applet example is given below.
Source
Refer the source code for the snmpPollerDemo example present in <examples/uiapplications/snmpPollerDemo.java> for more information.
AdventNet, Inc.
303
By default, it polls the sysUpTime value. A button is provided to toggle between start and stop polling. All the parameters, such as hostname, OID, etc. are set in the HTML file. The HTML file can be edited to change the following parameters according to the user preferences. <applet code=rmiAppletDemo.class width=600 height=200> <param name="MIBS" value="../../mibs/RFC1213-MIB"> <param name="RMISERVER" value=""> <param name="HOSTNAME" value="localhost"> <param name="COMMUNITY" value="public"> <param name="OID" value="sysUpTime.0"> <param name="SNMP_VERSION" value="0"> <param name="SNMP_PORT" value="161"> </applet> Note: The 'mib path' and 'host' are relative to the server. If the AdventNetSNMP RMI server (SnmpFactoryImpl) runs in a different host, set the value for the 'RMISERVER' in the HTML file as follows. <param name="RMISERVER" value="SomeHost:9000"> where, 'SomeHost' is the host machine name in which the RMI server runs '9000' is the port at which it is bound to the registry.
AdventNet, Inc.
304
The RMIAppletDemo example uses RMI Interfaces in a remote client applet. It uses the RMI SnmpPoller interface. Edit the rmiAppletDemo.html file to change the host and community.
Source
Refer the source code for the rmiAppletDemo example present in <examples/rmiclient/rmiAppletDemo.java> for more information.
Usage
appletviewer rmiAppletDemo.html
AdventNet, Inc.
305
Clicking the "Get Agent Data" button gets the value of the variable 1.5.0 (sysName) from the agent running in the local host. Clicking on the Property settings icon displays a dialog box through which host name, OID, v3-related parameters, etc. can be set overriding the values set in the HTML file. The HTML file can also be edited to change the following parameters according to the user preferences. param name="MIBS" value="../../mibs/RFC1213-MIB" param name="COMMUNITY" value="public" param name="OID" value="1.5.0" Following are the steps to view the applet in the web browser. Copy the settingsDemo*.class to the classes directory. Run the start_server.sh/bat file to start the Web server and SAS. The Web server is started in the port 8282 and SAS in any random port. Load the html file to start polling as follows.
AdventNet, Inc.
306
http://localhost:8282/applications/settingsDemo.html
Source
Refer the source code for the settingsDemo example present in <examples/uiapplications/settingsDemo.java> for more information.
AdventNet, Inc.
307
Source
Refer the source code for the lineGraphDemo example present in <examples/uiapplications/lineGraphDemo.java> for more information.
AdventNet, Inc.
308
Tutorials
Overview Data Retrieval Tutorials Data Altering Tutorials Traps and Inform Tutorials Table Handling Tutorials MIB Handling Tutorials Other Tutorials Complete Example
This section details about the various tutorials that are bundled with AdventNet SNMP API package and the instructions on setting up the environment to use them. The tutorials present in this section helps you get familiar with development using of AdventNet SNMP API. Example Java programs are available that can be compiled and run. Follow the links to learn more.
AdventNet, Inc.
309
Overview
Beans API Tutorial Low-Level API Tutorial MIBs API Tutorial SAS API Tutorial
This section explains the steps involved in developing applications and applets for SNMP management.
AdventNet, Inc.
310
AdventNet, Inc.
311
We will define the class and the static main function required for the Java applications. public class snmpexample { public static void main(String args[]) { To use the com.adventnet.snmp.snmp2 package, we need to instantiate and start the SnmpAPI class. The SnmpAPI class is a thread which monitors SNMP sessions and contains various SNMP parameters. We will enable the debug option by setting setDebug() to true. In the debug mode, the PDU data is printed in hex format. SnmpAPI api = new SnmpAPI(); api.setDebug(true); To communicate with SNMP entities, we need to instantiate the SnmpSession class. The open() method has to be invoked to get a socket for SNMP communication. Various parameters, such as remote host, remote port, version, community, retries, timeouts, etc. can be set using this class. SnmpSession session = new SnmpSession(api); session.open(); For our example, we use the setProtocolOptions() of the SnmpPDU class to set the host to which we make request. Use setCommand() to send an SNMP request. The command constants are defined in the SnmpAPI class. The following command sets the constant to GET_REQ_MSG to perform an SNMP GET operation. //Build GET Request PDU SnmpPDU pdu = new SnmpPDU(); UDPProtocolOptions option = new UDPProtocolOptions("localhost"); pdu.setProtocolOptions(option); //sets the host pdu.setCommand(SnmpAPI.GET_REQ_MSG); We will set the OID for which we have to query by instantiating the SnmpOID class. SnmpOID is the subclass of the SnmpVar class, which provides abstract methods to present a uniform interface for applications working with the SNMP variables. The addNull method in the SnmpPDU class adds a variable binding with the OID specified and a null variable value.
AdventNet, Inc.
312
SnmpOID oid = new SnmpOID(".1.3.6.1.2.1.1.1.0"); pdu.addNull(oid); After the SnmpPDU and the OID is setup using the above methods, it should be sent over a session to the peer SNMP entity. The method syncSend(pdu) is used to send synchronous requests. We use the printVarBinds() method to print the descriptive value of the OID and the variables. SnmpPDU result = session.syncSend(pdu); System.out.println(result.printVarBinds()); Finally, we close the session and the API thread. session.close(); api.close(); Now, we can compile the program, Snmpexample, and view the result. Refer the source code for Snmpexample present in <tutorials/low_level_api/Snmpexample.java> for more information. This simple program is used to explain the usage of the key classes. We will build on this examples to show how the remaining packages are used in the development of advanced applications.
AdventNet, Inc.
313
AdventNet, Inc.
314
AdventNet, Inc.
315
SNMP GET and GETNEXT are the SNMP operations performed to retrieve SNMP information. The SNMP GET operation retrieves one or more values from the managed agent's MIB. The GETNEXT operation performs the same for the next object in the tree of objects in the managed device. The mandatory values we need to provide are the host name in which the agent resides and the OID that needs to be queried. Note: The tutorial examples provided do not include code for checking versions, catching error messages, etc. More comprehensive examples that can be used as command line tools are distributed in the <applications> directory. These examples include the code for setting more options and parameters, provide error messages, and so on. A separate file named ParseOptions.java is provided to parse the various command line options.
AdventNet, Inc.
316
AdventNet, Inc.
317
Now, we can make a get request and print the results. Depending on the request type and the required result type, we can choose the methods in the SnmpTarget class. String result[] = target.snmpGetList(); for (int i=0; i < oids.length;i++) { System.out.println("OBJECTID: "+target.getObjectID(i)); System.out.println("Response:"+result[i]); } The releaseResources() method of SnmpTarget class can be called to close the sessions. Now, we can compile the program and view the result. Ensure that you provide the correct host name and the OID in the command-line. You can build similar applications effortlessly. For example, to perform an SNMP GETNEXT operation, all you have to do is change target.snmpGetList() to target.snmpGetNextList(). The rest remains the same. This example uses only a single parameter target.setPeerName() for setting the host name. The following parameters can also be included in the example. target.setCommunity() - community target.setTargetPort() - port target.setSnmpVersion() - version target.setRetries() - retry values target.setTimeout() - timeout values
Refer the source code of the following examples for more information. Tutorial Tutorial for SNMP GET Tutorial for SNMP GETNEXT Command line example for SNMP GET Command line example for SNMP GETNEXT Available in <tutorials/beans_ui_api/SnmpGet.java> <tutorials/beans_ui_api/SnmpGetNext.java <examples/applications/snmpget.java> <examples/applications/snmpgetnext.java>
AdventNet, Inc.
318
Apart from the above, the following JFC Swing components are used. JButton JTextField JLabel
We need to import the com.adventnet.snmp.beans and com.adventnet.snmp.ui packages along with JDK packages. import import import import javax.swing.*; java.awt.event.*; com.adventnet.snmp.beans.*; com.adventnet.snmp.ui.*;
We will define the class and the static main function required for the Java applications. We implement the ActionListener interface to respond to the user actions. We instantiate all the beans components we use. SnmpGetUI implements ActionListener { SnmpTarget target = new SnmpTarget(); // for snmp operations PropertySettings pptysettings = new PropertySettings(); // to change the properties during run-time JButton button = new JButton(); // do SNMP GET JButton button1 = new JButton(); // do SNMP GETNEXT JButton button2 = new JButton(); // clear the results JTextField textfield = new JTextField(); //enter the oid JTextField textfield1 = new JTextField(); //for displaying results JLabel label = new JLabel(); public static void main(String args[]) { We instantiate JFrame and include all our UI components in the frame.
Note: Users can include their own layouts and other components.
public class SnmpGetUI implements ActionListener { SnmpTarget target = new SnmpTarget(); // for snmp operations
AdventNet, Inc.
319
PropertySettings pptysettings = new PropertySettings(); // to change the properties during run-time JButton button = new JButton(); // do SNMP GET JButton button1 = new JButton(); // do SNMP GETNEXT JButton button2 = new JButton(); // clear the results JTextField textfield = new JTextField(); //enter the oid JTextField textfield1 = new JTextField(); //for displaying results JLabel label = new JLabel(); public static void main(String args[])> { SnmpGetUI snmpops = new SnmpGetUI(); //instantiate this class for our example //all the UI related stuff JFrame frame = new JFrame(); //use JFrame frame.setVisible(true); frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent evt) { System.exit(0); } } ); frame.setSize(615,400); frame.setTitle("Tutorial Example for SNMP Target and Property Settings bean"); frame.getContentPane().setLayout(null); frame.getContentPane().add(snmpops.label); snmpops.label.setBounds(105,40,105,25); snmpops.label.setText("Enter the OID"); frame.getContentPane().add(snmpops.textfield1); snmpops.textfield1.setBounds(210,40,140,25); frame.getContentPane().add(snmpops.textfield); snmpops.textfield.setBounds(30,80,490,85); frame.getContentPane().add(snmpops.button); snmpops.button.setBounds(80,195,105,35); snmpops.button.setText("GET"); frame.getContentPane().add(snmpops.button1); snmpops.button1.setBounds(185,195,105,35); snmpops.button1.setText("GET NEXT"); frame.getContentPane().add(snmpops.button2); snmpops.button2.setBounds(290,195,105,35); snmpops.button2.setText("Clear"); frame.getContentPane().add(snmpops.pptysettings); snmpops.pptysettings.setBounds(395,190,85,55); Now, we set some parameters for the SnmpTarget bean. In this example, we set the host name as the parameter for the Snmptarget bean. Various parameters, such as community, port, version, retry values, and timeout values can be included in the example.
AdventNet, Inc.
320
snmpops.target.setTargetHost("localhost"); Here, we have given the host name as localhost. While executing the program, this can be changed to the host name of your choice by using the Property Settings bean. We need to add the VetoableChangeListener to this component and register a listener to receive the events from this component. We register the SnmpTarget bean so that it is notified of any changes in the Property Settings bean and updated accordingly. snmpops.pptysettings.addVetoableChangeListener(snmpops.target); Now, we add ActionListeners to the button components so that it responds to the user actions. snmpops.button.addActionListener(snmpops); snmpops.button1.addActionListener(snmpops); snmpops.button2.addActionListener(snmpops); Now, we implement the actionPerformed() of the Action Listener interface so that we get the response. public void actionPerformed(ActionEvent e) { // if the user presses the get button, the SnmpTarget bean gets the OID from the // text field, does a SNMP GET operation and displays the results in the larger // text field. if (e.getActionCommand().equals("GET")) { target.setObjectID(textfield1.getText()); textfield.setText(target.snmpGet()); } // if the user presses the getnext button, the SnmpTarget bean // does a SNMP GETNEXT operation and displays the results in the larger // text field. else if (e.getActionCommand().equals("GET NEXT")) { textfield.setText(target.snmpGetNext()); } // if the user presses the clear button the contents in the // text field gets cleared else if (e.getActionCommand().equals("Clear")) { textfield.setText(""); } Now, we can compile the source and view the results. The resources used by this class are automatically garbage collected. There is no need to close the sessions or perform cleanup operations. You can build similar applications effortlessly. The tutorial examples provided do not include code for checking versions, catching error messages, and so on.
AdventNet, Inc.
321
Note: In this tutorial example, you have to perform a GET first and then GETNEXT.
Refer the source code for SnmpGetUI present in <tutorials/beans_ui_api/SnmpGetUI.java> for more information.
AdventNet, Inc.
322
We will define the class and the static main function required for the Java applications. The following code snippet gets the hostname and the OID as command line inputs. if(args.length < 2) { System.out.println("Usage : java snmpget hostname OID"); System.exit(0); } String remoteHost="args[0]"; String OID = "args[1]"; To use the com.adventnet.snmp.snmp2 package, we need to instantiate and start the SnmpAPI class. The SnmpAPI class is a thread which monitors the SNMP sessions and contains various SNMP parameters. We enable the debug by setting setDebug() to true. In the debug mode, the PDU data is printed in hex format. SnmpAPI api = new SnmpAPI(); api.setDebug(true); To communicate with the SNMP entities, we need to instantiate the SnmpSession class. The SnmpSession class is used to communicate with other SNMP peers. The open() method has to be invoked to get a socket for SNMP communications. Various parameters, such as remote host, remote port, version, community, retries, and timeouts, can be set using this class. SnmpSession session = new SnmpSession(api); session.open(); For our example, we use the setProtocolOptions() of the SnmpPDU class to set the host to which we make request. Use setCommand() to send an SNMP request. The command constants are defined in the SnmpAPI class. The following command sets the constant to GET_REQ_MSG to perform an SNMP GET operation.
AdventNet, Inc.
323
//Build GET Request PDU SnmpPDU pdu = new SnmpPDU(); //get the value from the command line UDPProtocolOptions option = new UDPProtocolOptions(remoteHost); pdu.setProtocolOptions(option); pdu.setCommand(SnmpAPI.GET_REQ_MSG); We will set the OID for which we have to query by instantiating the SnmpOID class. SnmpOID is the subclass of the SnmpVar class, which provides abstract methods to present a uniform interface for applications working with the SNMP variables. Multiple OIDs can be given as input. The addNull method in the SnmpPDU class adds a variable binding with the OID specified and a null variable value. for (int i=1; i < args.length; i++) { SnmpOID oid = new SnmpOID(OID); //gets the value from command-line pdu.addNull(oid); } After the SnmpPDU and the OID is setup using the above methods, it should be sent over a session to the peer SNMP entity. The method syncSend(pdu) is used to send synchronous requests. We use the printVarBinds() method to print the descriptive value of the OID and the variables. SnmpPDU result = session.syncSend(pdu); System.out.println(result.printVarBinds()); Finally, we close the session and the API thread. session.close(); api.close(); Now, we can compile the program and view the result. Ensure that you provide the correct host name and the OID in the command line. You can build similar applications effortlessly. For example, to perform an SNMP GETNEXT operation, all you have to do is to change pdu.setCommand (SnmpAPI.GET_REQ_MSG) to pdu.setCommand (SnmpAPI.GETNEXT_REQ_MSG). The rest of the code remain the same. We can modify this example further to receive the MIB file also as a command line input. In this case, we need to import com.adventnet.snmp.mibs package in addition to the com.adventnet.snmp.snmp2 package. After invoking the open() method of the SnmpSession class, we need to load the MIB file. The MIB files are loaded using the MibOperations class. This class provides method to load multiple MIBs. All modules loaded through a particular MibOperations instance are registered only with that particular MibOperations object and do not interfere with other MibOperations instances. Under normal circumstances, it is sufficient to have one MibOperations instance. The methods available in the mibs package allow to query the MIB data to retrieve numeric or named OID, look-up range validations, and extract outputs in readable formats. MibOperations mibops = new MibOperations(); try { mibops.loadMibModules(mibfile); } catch (Exception ex)
AdventNet, Inc.
324
{ System.err.println("Error loading MIBs: " + ex); } Then, invoke the setcommand() of the SnmpPDU class to send an SNMP request. The rest of the code remain the same. Refer the source code of the following examples for more information. Tutorial Tutorial for SNMP GET Tutorial for SNMP GETNEXT Command line example for SNMP GET Command line example for SNMP GETNEXT Available in <tutorials/low_level_api/SnmpGet.java> <tutorials/low_level_api/SnmpGetNext.java> <examples/low_level_api_examples/snmpapps/snmpget.java> <examples/low_level_api_examples/snmpapps/snmpgetnext.java>
AdventNet, Inc.
325
We need to pass the applet constructor for the bean components we use. SnmpTarget target = new SnmpTarget(this); //for snmp operations PropertySettings pptysettings = new PropertySettings(this); //to change the properties during run-time We need to make the necessary code changes to compile it as an applet. Refer the source code of the tutorial example for SNMP GET and GETNEXT (Applet) for more information. It is evident that although we develop an applet, we do not directly import the com.adventnet.snmp.sas package. The bean components itself can be specified to be used in the context of an application or an applet. Similarly, when we use the low-level API, the SnmpSession object should know whether it runs in an application or an applet. The SASClient class in the com.adventnet.snmp.snmp2 package provides a means for applets to transparently talk to SNMP devices through SAS getting around the security restrictions. Applets do not have to instantiate this class explicitly. When SnmpSession in the snmp2 package is opened, it instantiates a SASClient for communicating with SAS. Bean components, which are built on top of snmp2 package, uses this and therefore it is sufficient if we use the bean in the applet context. Now, we can compile the source and load and view the applet. Following are the several ways of loading and viewing the applet we have developed. Applet viewer Web browser by setting code and codebase Web browser by loading the jar
Depending on the way which we need to load and view applets, the HTML files are to be modified accordingly. Before loading the applets, we need to start SAS and the web server by using the start_server script. The web server is started on port 8282 and SAS is started on any available port. The SAS port information is written to the file SASPort.html in the specified directory.
AdventNet, Inc.
326
Note: In this tutorial example, you need to first perform the GET operation before performing GETNEXT. Refer the source code for MibBrowserApplet present in <tutorials/low_level_api/MibBrowserApplet.java> for more information.
AdventNet, Inc.
327
AdventNet, Inc.
328
We will define the class and the static main function required for the Java applications. public class SnmpGet_tcp { public static void main(String args[]) { We get the host name and the OID as command line inputs. if(args.length<2) { System.out.println("Usage : java SnmpGet_tcp hostname OID"); System.exit(0); } String remoteHost="args[0]"; String OID = "args[1]"; To use the com.adventnet.snmp.snmp2 package, we need to instantiate and start the SnmpAPI class. The SnmpAPI class is a thread which monitors SNMP sessions and contains various SNMP parameters. The start() method starts the SnmpAPI thread. We enable the debug by setting setDebug() to true. In the debug mode, the PDU data is printed in hex format. SnmpAPI api = new SnmpAPI(); api.start(); api.setDebug(true); To communicate with the SNMP entities, we need to instantiate the SnmpSession class. The SnmpSession class is used to communicate with other SNMP peers. SnmpSession session = new SnmpSession(api);
AdventNet, Inc.
329
We need to set the transport provider framework that we use. //choose your transport provider session.setProtocol(session.TRANSPORT_PROVIDER); We use the reference implementation provided to set the protocol to the TCP. The TcpProtocolOptionsImpl class is the implemention of the ProtocolOptions interface for TCP/IP. // set the protocol to the TCP ProtocolOptions options = new TcpProtocolOptionsImpl(remoteHost, 161, -1); session.setProtocolOptions(options); It is mandatory for all the protocol options to be set first on the SnmpSession object before opening the session. The open() method of the SnmpSession has to be invoked to get a socket for SNMP communications. Various parameters such as remote host, remote port, version, community, retries, and timeouts can be set using this class. For our example, we use the setPeername() to set the domain name of the host to which we make the request. try { session.open(); } catch (SnmpException e ) { System.err.println("Error opening socket: "+e); } session.setPeername(remoteHost); //gets the value from the command-line An SnmpPDU instance needs to be created to send any request to an SNMP peer. The SnmpPDU provides most of the methods related to communication parameters that are available with the SnmpSession and overrides the value in the session. Instantiate SnmpPDU and use setCommand() to send an SNMP send request. The command constants are defined in the SnmpAPI class. SnmpPDU pdu = new SnmpPDU(); pdu.setCommand( api.GET_REQ_MSG ); We set the OID or a list of OIDs for which we have to query by instantiating the SnmpOID class. SnmpOID is the subclass of the SnmpVar class which provides abstract methods to present a uniform interface for applications working with the SNMP variables. Multiple OIDs can be given as input. The OID can be given in the form x.x.x... or .x.x.x.... The OID given in the form .x.x.x is assumed to be fully qualified. The OID in the form x.x.x is not fully qualified and the SnmpAPI.Standard_Prefix is added to the OID. This prefix is static and can be changed by the user, but has to be applied across the entire application or applet. The addNull method in the SnmpPDU class adds a variable binding with the OID specified and a null variable value. for (int i=1; i < args.length; i++) { SnmpOID oid=new SnmpOID(OID); //gets the value from command-line pdu.addNull(oid); } We use the synchronous method, syncSend(pdu) to send the PDU. We use printVarBinds() to print the descriptive value of the OID and the variables.
AdventNet, Inc.
330
try { pdu = session.syncSend(pdu); } catch (SnmpException e) { System.err.println("Error sending SNMP request: "+e); } System.out.println(pdu.printVarBinds()); Finally, we close the session and stop the API thread. session.close(); api.close(); Now, we can compile the program and view the result. Ensure that you provide the correct host name and the OID in the command line. You can build similar applications effortlessly. For example, to perform an SNMP GETNEXT operation, all you have to do is to change pdu.setCommand(api.GET_REQ_MSG) to pdu.setCommand(api.GETNEXT_REQ_MSG). The rest of the code remain the same. This example uses a single session parameter session.setPeerName() for setting the host name. Following are the various session parameters that can be included in the example. session.setCommunity() - community session.setRemotePort() - port session.setVersion() - version session.setRetries() - retry values session.setTimeout() - timeout values
Refer the source code for SnmpGet_tcp present in <tutorials/low_level_api/SnmpGet_tcp.java> for more information.
AdventNet, Inc.
331
AdventNet, Inc.
332
public void setStringResult(String s){ } The releaseResources() method of SnmpTarget class can be called to close the sessions. Now, we can compile the program and view the result. Ensure that you provide the correct host name and the OID in the command line. Note: This example continuously polls the given variable in one second interval. To exit the application, press Ctrl + C or close the shell. Refer the source code for SnmpPolling present in <tutorials/beans_ui_api/SnmpPolling.java> for more information.
AdventNet, Inc.
333
The SET operation allows the management application or the manager to set (write) the value of an attribute of a managed object in the agent. To perform the SET operation, we need to provide the host name in which the agent resides, OID, the type, and the value for the managed object. Note: The tutorial examples provided do not include code for checking versions, catching error messages, etc. More comprehensive examples that can be used as command line tools are distributed with this package. These examples include the code for setting more options and parameters, provide error messages, and so on. A separate file named ParseOptions.java is provided to parse the various command line options.
AdventNet, Inc.
334
AdventNet, Inc.
335
target.getCommunity()); System.out.println("OBJECT ID: "+target.getObjectID()); System.out.println("Response: "+result); } catch (Exception e) { System.err.println("Set Error: "+e.getMessage()); } The releaseResources() method of SnmpTarget class can be called to close the sessions. It is evident that the high-level beans components are comparatively simpler and easier to use in the development. Now, we can compile the program and view the result. Ensure that you provide the correct host name and the OID in the command-line. Refer the source code of the following examples for more information. Tutorial Tutorial for SNMP SET Command line example for SNMP SET Available In <tutorials/beans_ui_api/SnmpSet.java> <examples/applications/snmpset.java>
AdventNet, Inc.
336
We need to import the com.adventnet.snmp.beans and com.adventnet.snmp.ui packages along with JDK packages. import import import import javax.swing.*; java.awt.event.*; com.adventnet.snmp.beans.*; com.adventnet.snmp.ui.*;
We will define the class and the static main function required for the Java applications. We implement the ActionListener interface to respond to the user actions. We also instantiate all the beans components we use. public class SnmpSetUI implements ActionListener { SnmpTarget target = new SnmpTarget(); PropertySettings pptysettings = new PropertySettings(); JTextArea textfield = new JTextArea(); MibTree mibtree = new MibTree(); JButton loadbutton = new JButton(); JButton unloadbutton = new JButton(); JButton setbutton = new JButton(); JButton clearbutton = new JButton(); JTextField textfield1 = new JTextField(); JLabel label = new JLabel(); public static void main(String args[]) { We load the RFC1213-MIB as the default MIB. This MIB is loaded in the MIB Tree component. try { mibtree.addMib("RFC1213-MIB"); }
AdventNet, Inc.
337
catch (Exception ex) { } Now, we set some parameters for the SnmpTarget bean. In this example, we will set the host name as the parameter for the Snmptarget bean. Various parameters, such as community, port, version, retry values, timeout values can be included in this example. snmpops.target.setTargetHost("localhost"); Here, we have given the host name as localhost. While executing the program, this can be changed to the host name of your choice by using the Property Settings bean. We need to add the VetoableChangeListener to this component and register a listener to receive the events from this component. We register the SnmpTarget bean so that it is notified of any changes in the Property Settings bean and updated accordingly. pptysettings.addVetoableChangeListener(target); Now, we add ActionListeners to the button components so that it responds to the user actions. loadbutton.addActionListener(this); unloadbutton.addActionListener(this); setbutton.addActionListener(this); clearbutton.addActionListener(this); Now, we implement the actionPerformed() of the Action Listener interface so that we get the following response. The Load MIB button displays a file chooser through which the desired MIB file can be loaded. The Unload MIB button unloads the selected MIB file. Select a leaf node in the MibTree, enter the value to be set in the text field and then click the Set button. If the set operation is allowed in the node, the value is set. The Clear button clears the text area. The Property Settings icon displays a dialog box through which any desired properties can be changed.
public void actionPerformed(ActionEvent e) { //if the user presses the Load MIB button if (e.getActionCommand().equals("Load MIB")) { JFileChooser filechooser = new JFileChooser(); filechooser.showDialog(mibtree, "open"); try { mibtree.addMib(filechooser.getSelectedFile().toString()); } catch (Exception ex) { } } // if the user presses the unload mib button else if (e.getActionCommand().equals("Unload MIB")) { try { mibtree.deleteMib(mibtree.getSelectedMibModule().getName().toString()); }
AdventNet, Inc.
338
catch (Exception ex) { } } // if the user selects a leaf node, enters a value in the textfield and presses the SET button else if (e.getActionCommand().equals("SET")) { target.setObjectID((mibtree.getSelectedMibNode().getNumberedOIDString() toString()+".0")); try { target.snmpSet(textfield1.getText()); } >catch (Exception ex) { System.err.println("Set Error: "+ex.getMessage()); } textfield.setText("Response PDU received from " +target.getTargetHost()+ ",community: " + target.getCommunity()+"\n"+"OBJECT ID: "+target.getObjectID()+"\n"+ "RESPONSE: "+textfield1.getText()); } // if the user presses the clear button else if (e.getActionCommand().equals("Clear")) { textfield.setText(""); } } Now, we can compile the source and view the results. The releaseResources() method of SnmpTarget class can be called to close the sessions. The tutorial examples provided do not include code for checking versions, catching error messages, etc. The screenshot of this tutorial example program is as follows.
Refer the source code for SnmpSetUI present in <tutorials/beans_ui_api/SnmpSetUI.java> for more information.
AdventNet, Inc.
339
AdventNet, Inc.
340
SnmpVar var = null; try { var = SnmpVar.createVariable(value, >dataType); //value taken from the command line } catch(SnmpException e) >{ System.err.println("Cannot create variable: " + oid + " with value: " + value); return; } A varbind is a combination of an OID and an SNMP variable The SnmpVarBind class is used for variables and methods needed for variable bindings. SnmpVarBind contains SnmpOID and SnmpVar, where the SnmpOID is the OID and the SnmpVar, the value. SnmpVarBind varbind = new SnmpVarBind(oid, var); Now, we need to add this varbind to the PDU. The SnmpPDU class provides methods to work with the variable bindings. pdu.addVariableBinding(varbind); We use the synchronous method syncSend(pdu) to send the PDU. We use printVarBinds() to print the descriptive value of the OID and the variables. SnmpPDU result = session.syncSend(pdu); System.out.println("Response PDU received from " +result.getAddress()+ ", community: " + result.getCommunity()) System.out.println(result.printVarBinds()); Finally, we close the session and the API thread. session.close(); api.close(); Now we can compile and run the program and view the result. We can modify this example further to receive the MIB file also as a command line input. In this case, we need to import com.adventnet.snmp.mibs package in addition to the com.adventnet.snmp.snmp2 package. After invoking the open() method of the SnmpSession class, we need to load the MIB file. The MIB files are loaded using the MibOperations class. This class provides method to load multiple MIBs. All modules loaded through a particular MibOperations instance are registered with only that particular MibOperations object and do not interfere with other MibOperations instances. Under normal circumstances, it is sufficient to have one MibOperations instance. The methods available in the mibs package allows to query the MIB data to retrieve numeric or named OID, look-up range validations, and extract outputs in readable formats. MibOperations mibops = new MibOperations(); try { mibops.loadMibModules(mibfile); }
AdventNet, Inc.
341
catch (Exception ex) { System.err.println("Error loading MIBs: "+ex); } Then, invoke the setcommand() of the SnmpPDU class to send an SNMP SET request. The rest of the code remain the same. Refer the source code of the following examples for more information. Tutorial Tutorial for SNMP SET Command line example for SNMP SET Available In <tutorials/low_level_api/snmpset.java> <examples/low_level_api_examples/snmpapps/snmpset.java>
AdventNet, Inc.
342
Trap Tutorials
Receive Trap Using High-Level API Send Trap Using High-Level API Receive Trap (UI) Using High-Level API Send and Receive Trap (UI) Using High-Level API Receive Trap Using TrapBrowser Receive Trap Using Low-Level API Send Trap Using Low-Level API Receive Traps for Applets
Traps are unsolicited messages sent by an agent to the management stations to report the conditions of the managed node. The following tutorials explain the steps involved in developing simple applications to send and receive the trap messages. Note: The tutorial examples provided do not include code for checking versions, catching error messages, etc. More comprehensive examples that can be used as command line tools are distributed with this package. These examples include the code for setting more options and parameters, provide error messages, and so on. A separate file named ParseOptions.java is provided to parse the various command line options.
AdventNet, Inc.
343
We use these classes in our tutorial example. We need to import the com.adventnet.snmp.beans package. >import com.adventnet.snmp.beans.*; We will define the class and the static main function required for the java applications. We need to implement the Trap Listener interface and instantiate the SNMP Trap Receiver bean. public class SnmpTrapd implements TrapListener { SnmpTrapReceiver trapreceiver = new SnmpTrapReceiver(); public static void main(String args[]) { We set the port in which the trap is received and register the trap listener. trapreceiver.setPort(8001); trapreceiver.addTrapListener(this); //register the listener for trap events System.out.println("Waiting to receive traps ......."); The listener invokes the receivedTrap(TrapEvent e) when the trap is received by the trap receiver bean. The TrapEvent event contains the trap data. Now, we receive the traps and print the results. public void receivedTrap(TrapEvent trapEvent) { //receive traps System.out.println("TrapEvent received. "); System.out.println("Received a trap from:"+trapEvent.getRemoteHost()+ " in the port "+ trapreceiver.getPort()); System.out.println("Community is:"+trapEvent.getCommunity()); System.out.println("Agent Address is:"+trapEvent.getAgentAddress()); System.out.println("Enterprise OID:"+trapEvent.getEnterprise()); System.out.println("Trap Variable OID:"+trapEvent.getObjectID(0)); System.out.println("Continues waiting to receive traps ......."); }
AdventNet, Inc.
344
Now, we can compile and run the program and view the result. The application waits for traps. If any trap message is received at port 8001, the application prints the trap information. Refer the source code of the following examples for more information. Tutorial Tutorial for receiving traps Command line example for receiving traps Available In <tutorials/beans_ui_api/SnmpTrapd.java> <examples/applications/trapreceiver.java>
AdventNet, Inc.
345
All the above values can be received as command-line inputs. We use the SnmpTarget bean to send the trap message. We need to complete the necessary steps. Refer GET, GETNEXT, and SET tutorials for detailed discussion. To send a v1 trap and print the results, we use the snmpSendTrap() in the SnmpTarget bean. try { target.snmpSendTrap(enterprise, agenthost, generictype, specifictype, uptime, values); System.out.println("Response PDU received from " +target.getTargetHost()+ ", community: " + target.getCommunity()); System.out.println("OBJECT ID: "+target.getObjectID()); } catch (Exception e) { System.err.println("Set Error: "+e.getMessage()); } Now, we can compile and run the program and view the result. Refer the source code of the following examples for more information. Tutorial Tutorial for sending SNMPv1 trap Command line example for sending SNMPv1 trap Command line example for sending SNMPv2c/v3 trap Available In <tutorials/beans_ui_api/SnmpSendTrap.java> <examples/applications/sendtrap.java> <examples/applications/sendv2trap.java>
AdventNet, Inc.
346
We need to import the com.adventnet.snmp.beans and com.adventnet.snmp.ui packages along with JDK packages. import import import import javax.swing.*; java.awt.event.*; com.adventnet.snmp.beans.*; com.adventnet.snmp.ui.*;
We will define the class and the static main function required for the Java applications. To respond to the user actions, we implement the ActionListener interface and to listen for the traps we implement the TrapListener interface. We also instantiate all the bean components we use. public class SnmpTrapdUI implements TrapListener, ActionListener { SnmpTrapReceiver trapreceiver = new SnmpTrapReceiver (); JTextArea textfield = new JTextArea (); JButton clearbutton = new JButton (); public static void main(String args[]) { Now, we set some parameters for the SnmpTrapReceiver bean. trapreceiver.setPort("8001"); // port in which the trap is received We put the following message in the text field so that the user is aware that the program is waiting to receive the traps. textfield.setText ("Waiting to receive traps in the port " + trapreceiver.getPort () + "......."); Now, we add the TrapListener to the SnmpTrapReceiver for the trap events and ActionListener to the button component so that it responds to the user actions. trapreceiver.addTrapListener(this); clearbutton.addActionListener(this); Now, we implement the receivedTrap() of the TrapListener interface and the actionPerformed() of the Action Listener interface so that we get the following response.
AdventNet, Inc.
347
public void receivedTrap (TrapEvent trapEvent) //if the trap is received by the program { textfield.setText ("TrapEvent received." + "\n" + "Received a trap from:" + trapEvent.getRemoteHost () + " in the port " + trapreceiver.getPort () + "\n" + "Community is:" + trapEvent.getCommunity () + "\n" + "Agent Address is:" trapEvent.getAgentAddress () + "\n" + "Enterprise OID:" + trapEvent.getEnterprise () + "\n" + "Trap Variable OID:"+ trapEvent.getObjectID (0) + "\n" + "Continues waiting to receive traps in the port " + trapreceiver.getPort () + "......."); } public void actionPerformed(ActionEvent e) // if the user presses the clear button { textfield.setText("Waiting to receive traps in the port " + trapreceiver.getPort ()+ "......."); } Now, we can compile the source and view the results. The releaseResources() method of SnmpTarget class can be called to close the sessions. The screenshot of this tutorial example program is as follows.
Refer the source code for SnmpTrapdUI present in <tutorials/beans_ui_api/SnmpTrapdUI.java> for more information.
AdventNet, Inc.
348
We need to import the com.adventnet.snmp.beans and com.adventnet.snmp.ui packages along with JDK packages. import import import import javax.swing.*; java.awt.event.*; com.adventnet.snmp.beans.*; com.adventnet.snmp.ui.*;
We will define the class and the static main function required for the Java applications. We implement the ActionListener interface to respond to the user actions. To listen for the traps, we implement the TrapListener interface. We also instantiate all the beans components we use. public class SnmpSendTrapUI implements TrapListener, ActionListener { SnmpTarget target = new SnmpTarget(); SnmpTrapReceiver trapreceiver = new SnmpTrapReceiver(); JTextArea textfield = new JTextArea(); JButton clearbutton = new JButton(); JButton setbutton = new JButton(); String values [] = {"testing"}; // for sending trap public static void main(String args[]) { Now, we set some parameters for the SnmpTrapReceiver bean. trapreceiver.setPort("8001"); // port in which the trap is received We put the following message in the text field so that the user is aware that the program is waiting to receive the traps. textfield.setText ("Waiting to receive traps in the port " + trapreceiver.getPort() + "......."); The SnmpTarget bean is used for sending traps. The snmpSendTrap() needs the MIB file to be loaded for sending the traps. Therefore, we use loadMibs() in the SnmpTarget bean to load our MIB file.
AdventNet, Inc.
349
try { target.loadMibs("RFC1213-MIB"); } catch (Exception e) { System.err.println("Set Error: "+e.getMessage()); } Now, we add TrapListener to SnmpTrapReceiver for the trap events and ActionListener to the button component so that it responds to the user actions. trapreceiver.addTrapListener(this); clearbutton.addActionListener(this); setbutton.addActionListener(this); Now, we implement receivedTrap() of the TrapListener interface and actionPerformed() of the Action Listener interface so that we get the following response. public void receivedTrap (TrapEvent trapEvent) //if the trap is received by the program { textfield.setText ("TrapEvent received." + "\n" + "Received a trap from:" + trapEvent.getRemoteHost () + " in the port " + trapreceiver.getPort () + "\n" + "Community is:" + trapEvent.getCommunity () + "\n" + "Agent Address is:" + trapEvent.getAgentAddress () + "\n" + "Enterprise OID:" + trapEvent.getEnterprise () + "\n" +"Trap Variable OID:" + trapEvent.getObjectID (0) + "\n" + "Continues waiting to receive traps in the port " + trapreceiver.getPort () + "......."); } public void actionPerformed(ActionEvent e) // if the user presses the send trap button this hard-coded trap information is sent if (e.getActionCommand().equals("Send Trap")) { target.setTargetPort(8001 ); target.setObjectID("1.5.0"); try { target.snmpSendTrap("1.2.0", "localhost", 0, 6, 1000, values); } catch (Exception ex) { System.err.println("Set Error: "+ ex.getMessage()); } } else if (e.getActionCommand().equals("Clear")) { // if the user presses the clear button { textfield.setText ("Waiting to receive traps in the port " + trapreceiver.getPort () + "......."); } } Now, we can compile the source and view the results. The releaseResources() method of SnmpTarget class can be called to close the sessions.
AdventNet, Inc.
350
Refer the source code for SnmpSendTrapUI present in <tutorials/beans_ui_api/SnmpSendTrapUI.java> for more information.
AdventNet, Inc.
351
We need to import the com.adventnet.snmp.beans and com.adventnet.snmp.ui packages along with JDK packages. import import import import javax.swing.*; java.awt.event.*; com.adventnet.snmp.beans.*; com.adventnet.snmp.ui.*;
We will define the class and the static main function required for the Java applications. We need to implement the ActionListener interface to respond to the user actions, TrapListener interface to listen for the traps and TrapParserListener interface to respond for incoming ParsedTrapEvent. We also instantiate all the bean components we use. public class SnmpTrapBrowser implements TrapListener, TrapParserListener, ActionListener { SnmpTarget target = new SnmpTarget(); SnmpTrapReceiver trapreceiver = new SnmpTrapReceiver(); TrapBrowser trapbrowser = new TrapBrowser(); TrapParserBean trapparser = new TrapParserBean(); JButton setbutton = new JButton(); String values [] = {"testing"}; // for sending trap public static void main(String args[]) { Now, we set some parameters for the SnmpTrapReceiver bean. trapreceiver.setPort("8001"); / port in which the trap is received
AdventNet, Inc.
352
We set the parser file name for the TrapParser bean. The conditions specified in the file is used by the bean to parse the trap events. trapparser.setFileName("new_trap_parser.parser"); The SnmpTarget bean is used for sending traps. The snmpSendTrap() needs the MIB file to be loaded for sending the traps. Therefore, we use the loadMibs() in SnmpTarget bean to load our MIB file. try { target.loadMibs("RFC1213-MIB"); } catch (Exception e) { System.err.println("Set Error: "+e.getMessage()); } Now, we add TrapListener to SnmpTrapReceiver for the trap events, ParserListener to TrapParser for ParsedTrapEvents and ActionListener to the button component so that it responds to the user actions. trapreceiver.addTrapListener(this); trapparser.addParserListener(this); setbutton.addActionListener(this); Now, we implement receivedTrap() of the TrapListener interface, eventParsed() of TrapParserBean, and actionPerformed() of the Action Listener interface so that we get the following response. public void actionPerformed(ActionEvent e) { // if the user presses the send trap button ths hard-coded trap information is sent target.setTargetPort( 8001 ); target.setObjectID("1.5.0"); try { target.snmpSendTrap("1.2.0", "localhost", 0, 6, 1000, values); } catch (Exception ex) { System.err.println("Set Error: "+ex.getMessage()); } } public void receivedTrap(TrapEvent trapEvent) { //the TrapParserBean parses the traps received by the SnmpTrapReceiver bean trapparser.parseEvtAndFire(trapEvent); } public void eventParsed(ParsedTrapEvent parseevent) { //the TrapBrowser displays the ParsedTrapEvent in a Table format trapbrowser.displayEvent(parseevent); } Now, we can compile the source and view the results. The releaseResources() method of SnmpTarget class can be called to close the sessions.
AdventNet, Inc.
353
Refer the source code for SnmpTrapBrowser present in <tutorials/beans_ui_api/SnmpTrapBrowser.java> for more information. Usage of TrapBrowser and TrapParser are explained in this example.
AdventNet, Inc.
354
AdventNet, Inc.
355
community: " + pdu.getCommunity()); System.out.println("Enterprise: " + pdu.getEnterprise()); System.out.println("Agent: " + pdu.getAgentAddress()); System.out.println("TRAP_TYPE: " + pdu.getTrapType(); System.out.println("SPECIFIC NUMBER: " + pdu.getSpecificType()); System.out.println("Time: " + pdu.getUpTime()+"\nVARBINDS:"); System.out.println(pdu.printVarBinds()); System.out.println("Continues waiting to receive traps in the port "+session.getLocalPort() +"......."); return true; } The debugprint is used for printing any debug information. public void debugPrint(String debugOutput) { System.out.println(debugOutput); return; }
AdventNet, Inc.
356
Now we can compile and run the program and view the result. The application waits for traps. If any trap message is received at the port 8001, the application prints the trap information. We can modify this example further to receive the MIB file as a command line input. Refer the source code of the following examples for more information. Tutorial Tutorial for receiving traps using callback() Tutorial for receiving traps using receive() Command line example for receiving traps Available In <tutorials/low_level_api/SnmpTrapd.java> <tutorials/low_level_api/SnmpTrapd_one.java> <examples/low_level_api_examples/snmpapps/snmptrapd.java>
AdventNet, Inc.
357
All the above values can be received as command line inputs. if(args.length < 8) { System.out.println("Usage:java SnmpSendTrap hostname enterprise agent-addr generic-trap specific-trap timeticks OID type value"); System.exit(0); } String remoteHost = args[0]; String enterprise = args[1]; String agentaddr = args[2]; String generictrap = args[3]; String specifictrap = args[4]; String timeticks = args[5]; String OID = args[6]; String type = args[7]; String value = args [8]; We need to instantiate and start SnmpAPI and open SnmpSession. By convention, the traps are received at the port 162. In this example, we set the port to 8001. /Set port SnmpPDU pdu = new SnmpPDU(); UDPProtocolOptions option = new UDPProtocolOptions(remoteHost); pdu.setProtocolOptions(option); //sets the host in which the agent is running option.setRemotePort(8001); Instantiate SnmpPDU and use setCommand() to send an SNMP TRAP request. The command constants are defined in the SnmpAPI class. SnmpPDU pdu = new SnmpPDU(); pdu.setCommand(SnmpAPI.TRP_REQ_MSG); We fill in all the v1 trap PDU fields that are received from the command line. SnmpOID oids = new SnmpOID(enterprise); pdu.setEnterprise(oids);
AdventNet, Inc.
358
pdu.setAgentAddress(InetAddress.getByName(agentaddr)); pdu.setTrapType(Integer.parseInt(generictrap)); pdu.setSpecificType(Integer.parseInt(specifictrap pdu.setUpTime(Integer.parseInt(timeticks)); Now, we build the variable bindings with the given OID, type, and value. In this example, we check only for the type STRING. The code should include all the known SNMP data types. SnmpOID oid = new SnmpOID(OID); byte dataType; if (type.equals("STRING")) { dataType = SnmpAPI.STRING; } else { System.err.println("Invalid variable type: " + type); return; } SnmpVar var = null; try { var = SnmpVar.createVariable(value, dataType); } catch(SnmpException e) { System.err.println("Cannot create variable: " + oid + " with value: " + value); return; } SnmpVarBind varbind = new SnmpVarBind(oid, var); pdu.addVariableBinding(varbind); We use the asynchronous method send(pdu) to send the PDU. session.send(pdu); Finally, we close the session and the API thread. session.close(); api.close(); System.exit(0); Now, we can compile and run the program and view the result. We have also provided another example in which all the trap fields are given. You need to give only the remote host name as the input for running the application. We can modify this example further to receive the MIB file, in addition to the above-mentioned values, as a command line input. Refer the source code of the following examples for more information. Tutorial Tutorial I for sending SNMPv1 trap Tutorial II for sending SNMPv1 trap Available In <tutorials/low_level_api/SnmpSendTrap.java> <tutorials/low_level_api/SnmpSendTrap_one.java>
AdventNet, Inc.
359
Tutorial Command line example for sending SNMPv1 trap Command line example for sending SNMPv2c trap Command line example for sending SNMPv3 trap
AdventNet, Inc.
360
Define the required class and the static main function. We implement the SnmpClient Interface to receive the traps. public class TrapReceiverApplet extends JApplet implements SnmpClient { Instantiate the SnmpAPI class and other UI components. JTextArea text; SnmpAPI api; // The SNMP API instance public void init() { getContentPane().setLayout(null); text = new JTextArea("Waiting to receive traps\n"); text.setEditable(false); getContentPane().add(text); text.setBounds(30,80,490,85); } We need to start SnmpAPI and open SnmpSession. We have to add the SnmpClient interface implementation to the session to invoke callback, authenticate, and debugging functions. Moreover, by convention, the traps are received at the port 162. In this example, we set the local port to 8001. api = new SnmpAPI( ); api.start( ); api.setDebug(true); SnmpSession session = new SnmpSession(api); session.setCallbackthread(true); session.addSnmpClient(this); int port = 8001; // set port to listen for traps try { session.open(this); //Open session for use by the applet } catch (SnmpException e) { System.err.println("Error opening session:"+e.getMessage()); System.exit(1); }
AdventNet, Inc.
361
If applets wish to receive traps and notifications, they need to register with SAS. During registration, applets can specify the port on which SAS should listen for traps. Applets get a reference to the SASClient class used by the session using the getSASClient() method available in SnmpSession. SASClient sasClient = session.getSASClient(); if (sasClient.isConnected( ) == true) { try { sasClient.reqTraps(port); } catch(IOException ioe) { System.err.println("Error " + ioe.getMessage( )); } text.append("Listening for Traps on port: " + port + "\n\n"); } else { text.append("SAServer not Connected \n"); } } Now, we need to implement the three methods of the SnmpClient interface. public boolean callback(SnmpSession session, SnmpPDU pdu, int reqid) { if (pdu.getCommand() != api.TRP_REQ_MSG) System.err.println("Non trap PDU received"); else showStatus("Trap PDU received"); text.append("Trap received from: " +pdu.getRemoteHost() + ", community: " + pdu.getCommunity() + "\n"); return true; } public void debugPrint(Strings) { System.err.println(s); } public boolean authenticate(SnmpPDU pdu, String community) { return true; } Now, we can compile the source and load and view the applet. Refer GET, GETNEXT for a discussion on the different ways of loading the applet and different HTML files we need to create. The applet waits for traps. If any trap message is received at the port 8001, the applet prints the trap information. Refer the source code of the HTML file for loading the SnmpGetApplet example. Refer the source code for TrapReceiverApplet present in <tutorials/sas_api/TrapReceiverApplet.java> for more information.
AdventNet, Inc.
362
Refer the source code for viewTrap present in <tutorials/sas_api/viewTrap.java> for more information.
AdventNet, Inc.
363
The above tutorials are for developing simple UI applications for displaying table information. These tutorials explain the steps involved in developing the applications that retrieve SNMP tables from a remote agent using various bean components. Note: The tutorial examples provided do not include code for checking versions, catching error messages, etc. More comprehensive examples that can be used as command line tools are distributed with this package. These examples include the code for setting more options and parameters, provide error messages, and so on. A separate file named ParseOptions.java is provided to parse the various command line options.
AdventNet, Inc.
364
We need to import the com.adventnet.snmp.ui package along with JDK packages. import javax.swing.*; import java.awt.event.*; import com.adventnet.snmp.ui.*; We will define the class and the static main function required for the Java applications. We instantiate all the bean components we use. In the JScrollpane, we include the TableBean instance. public class SnmpGetTableUI_one { TableBean tablebean = new TableBean (); JScrollPane scrollpane = new JScrollPane(tablebean); public static void main(String args[]) { We set some parameters for TableBean. tablebean.setHost("localhost"); tablebean.setCommunity("public"); We need to load the MIB file and set the table OID. For tutorial purposes, we load the RFC 1213-MIB and set the table OID to tcpConnTable. try { tablebean.setMibModules("RFC1213-MIB"); tablebean.setTableOID("tcpConnTable"); }catch (Exception ex) { System.err.println("Error: "+ex); } Now, we can compile the source and view the results. The releaseResources() method of SnmpTarget class can be called to close the sessions. You can build similar applications effortlessly. For example, you can include the PropertySettings bean to change the properties, MibTreebean to load the MIBs, and so on.
AdventNet, Inc.
365
Refer the source code of the following examples for more information. Tutorial Tutorial for using SnmpTableModel bean Comprehensive example on using TableBean Available In <tutorials/beans_ui_api/SnmpGetTableUI_one.java> <examples/uiapplications/tableBeanDemo.java>
AdventNet, Inc.
366
AdventNet, Inc.
367
} for (int i=0;i < table.getColumnCount();i++) // print column names sb.append(table.getColumnName(i)+" \t"); System.out.println(sb.toString()); StringBuffer sb2 = new StringBuffer(); for (int i=0;i < table.getColumnCount();i++) for (int j=0;j < table.getRowCount();j++) sb2.append(table.getValueAt(j,i)+" \t"); System.out.println(sb2.toString()); To release the resources used by this class, the releaseResources() method of SnmpTable is invoked. Now, we can compile the program and view the result. Ensure that you provide the correct host name and the correct table OID in the command line. Refer the source code of the following examples for more information. Tutorial Available In Tutorial for retrieving SNMP table <tutorials/beans_ui_api/SnmpGetTable_one.java> Command line example for retrieving SNMP <examples/applications/getSnmpTable.java> table
AdventNet, Inc.
368
AdventNet, Inc.
369
for (int i=0;i < table.getColumnCount();i++) // print column names sb.append(table.getColumnName(i)+" \t"); System.out.println(sb.toString()); StringBuffer sb2 = new StringBuffer(); for (int i=0;i < table.getColumnCount();i++) for (int j=0;j < table.getRowCount();j++) sb2.append(table.getValueAt(j,i)+" \t"); System.out.println(sb2.toString()); To release the resources used by this class, the releaseResources() method of SnmpAugmentTable is invoked. Now, we can compile the program and view the result. Ensure that you provide the correct host name and the correct table OID in the command line. Refer the source code of the following examples for more information. Tutorial Tutorial for retrieving SNMP Augment table Command line example for retrieving SNMP Augment table Available In <tutorials/highlevelapi/GetSnmpAugmentTable.java> <examples/applications/getSnmpAugmentTable.java>
AdventNet, Inc.
370
In this tutorial example, we develop a simple UI application using the SnmpTableModel bean for displaying the table information. The SnmpTableModel component is actually not a user-interface component but designed for working with the JFC/Swing components. We use this component along with the JTable component in our example. The following bean components are used in this example. SnmpTableModel JTable JFrame JScrollPane
We need to import the com.adventnet.snmp.ui package along with JDK packages. import javax.swing.*; import java.awt.event.*; import com.adventnet.snmp.ui.*; We will define the class and the static main function required for the Java applications. We instantiate all the bean components we use. In the JTable, we include the SnmpTableModel instance and include this table in a scrollpane. public class SnmpGetTableUI { SnmpTableModel datatable = new SnmpTableModel (); JTable table = new JTable(datatable); // instantiate JTable with SnmpTableModel instance //include this table in a scrollpane JScrollPane scrollpane = new JScrollPane(table); public static void main(String args[]) { We set some parameters for the SnmpTableModel. datatable.setTargetHost("localhost"); datatable.setCommunity("public"); We need to load the MIB file and set the table OID. For tutorial purposes, we load the RFC 1213-MIB and set the table OID for tcpConnTable. try { datatable.loadMibs("RFC1213-MIB");
AdventNet, Inc.
371
datatable.setTableOID ("tcpConnTable"); } catch (Exception ex) { System.err.println("Error: "+ex); } Now, we can compile the source and view the results. The resources used by this class can be released by using the releaseResources() method of SnmpTableModel. You can build similar applications effortlessly. For example, you can include PropertySettings bean to change the properties, MibTreebean to load the MIBs, and so on. The tutorial examples provided do not include code for checking versions, catching error messages, etc. The screenshot of this tutorial example program is as follows.
Refer the source code of the following examples for more information. Tutorial Tutorial for using SNMPTableModel bean Comprehensive example on using SNMPTableModel bean Available In <tutorials/beans_ui_api/SnmpGetTableUI.java> <examples/uiapplications/swingtable.java>
AdventNet, Inc.
372
We need to import the com.adventnet.snmp.ui package along with JDK packages. import javax.swing.*; import java.awt.event.*; import com.adventnet.snmp.ui.*; We will define the class and the static main function required for the Java applications. We instantiate all the beans components we use. public class SnmpGetLargeTable { SnmpTablePanel tablepanel = new SnmpTablePanel (); public static void main(String args[]) { We set some parameters for SnmpTablePanel. tablePanel.setTargetHost("localhost"); tablepanel.setCommunity("public"); We need to load the MIB file and set the table OID. For tutorial purposes, we load the RFC1213-MIB and set the table OID for ifTable. try { tablepanel.loadMibs("RFC1213-MIB"); tablepanel.setTableOID("ifTable"); } catch (Exception ex) { System.err.println("Error: "+ex); } Now, let us compile the source and view the results. The releaseResources() method of SnmpTarget class can be called to close the sessions. You can build similar applications effortlessly. For example, you can include PropertySettings Bean to change the properties, MibTreebean to load the MIBs, and so on.
AdventNet, Inc.
373
Refer the source code of the following examples for more information. Tutorial Tutorial for using SNMPTablePanel Comprehensive example on using SNMPTablePanel Available In <tutorials/beans_ui_api/SnmpGetLargeTable.java> <examples/uiapplications/largetable.java>
AdventNet, Inc.
374
We will define the class and the static main function required for the java applications. public class SnmpGetTable { public static void main(String args[]) { We get the hostname and the OID as the command line inputs. The OID should be the table OID. if( args.length < 2) { System.out.println("Usage : java SnmpGetTable hostname oid"); System.exit(0); } String remoteHost="args[0]"; String OID ="args[1]"; We use the SnmpTarget bean for our SNMP operations. Instantiate the SnmpTarget bean and set the host name. SnmpTarget target = new SnmpTarget(); target.setTargetHost(remoteHost); We load the MIB file. try { target.loadMibs("RFC1213-MIB"); } catch (Exception ex) { System.err.println("Error loading MIBs: "+ex); } We instantiate the MibOperations class from the mibs package and get the table OID and the table MIB node. MibOperations mibops = target.getMibOperations(); // instantiate the MibOperations class SnmpOID tableoid = mibops.getSnmpOID(oid); // get table OID MibNode tablenode = mibops.getMibNode(tableoid); // get table MIB node
AdventNet, Inc.
375
Now, we need to create the OID array that is used by the SnmpTarget bean. Vector columns = tablenode.getTableItems(); String oids[] = new String[columns.size()]; for (int i=0; i < oids.length;i++) oids[i]="(String)columns.elementAt(i);" Now, we set this OID list in the SnmpTarget bean and perform a successive GETNEXT to get the results. target.setObjectIDList(oids); // set the oid list String result[][] = target.snmpGetAllList(); // store the result in a two dimensional array Now, we can print the table. System.out.println("Getting table. Table items:"); StringBuffer sb = new StringBuffer(); // first print the column names for (int i=0; i < oids.length; i++) sb.append(oids[i]+" \t"); sb.append("\n"); // next print each table item for (int j=0;j < result.length;j++) { // for each row for (int i=0;i < result[j].length;i++) // for each column sb.append(result[j][i]+"\t"); sb.append("\n"); } System.out.println(sb.toString()); The resources used by this class can be released by using the releaseResources() method of SnmpTableModel.Now we can compile the program and view the result. Ensure that you provide the correct host name and the OID in the command line. Refer the source code of the following examples for more information. Tutorial Availale In Tutorial for retrieving SNMP table <tutorials/beans_ui_api/SnmpGetTable_one.java> Command line example for retrieving SNMP <examples/applications/gettable.java> table
AdventNet, Inc.
376
This section explains some of the examples related to MIBs. Note: The tutorial examples provided do not include code for checking versions, catching error messages, etc. More comprehensive examples that can be used as command line tools are distributed with this package. These examples include the code for setting more options and parameters, provide error messages, and so on. A separate file named ParseOptions.java is provided to parse the various command line options.
AdventNet, Inc.
377
We need to import the com.adventnet.snmp.beans and com.adventnet.snmp.ui packages along with JDK packages. import import import import javax.swing.*; java.awt.event.*; com.adventnet.snmp.beans.*; com.adventnet.snmp.ui.*;
We will define the class and the static main function required for the Java applications. We implement the ActionListener interface to respond to the user actions. We also instantiate all the bean components we use. public class SnmpMibTree implements ActionListener { MibTree mibtree = new MibTree(); JTextArea textfield = new JTextArea(); JButton loadbutton = new JButton(); JButton unloadbutton = new JButton(); JButton describebutton = new JButton(); JButton clearbutton = new JButton(); public static void main(String args[]) { We load the RFC1213-MIB as the default MIB. This MIB is loaded in the MIBTree component. try { mibtree.addMib("RFC1213-MIB"); } catch (Exception ex) { } Now, add ActionListeners to the button components so that they respond to the user actions. loadbutton.addActionListener(this); unloadbutton.addActionListener(this); describebutton.addActionListener(this); clearbutton.addActionListener(this);
AdventNet, Inc.
378
Now, we implement actionPerformed() of the Action Listener interface so that we get the following response. The Load MIB button displays a file chooser through which the desired MIB file can be loaded. The Unload MIB button unloads the selected MIB file. Selecting a leaf node in the MIB tree and clicking the Description button displays the details of the node in the text area. The MibTree component has several methods which can be used for this purpose. The Clear button clears the text area.
public void actionPerformed(ActionEvent e) { //if the user presses the Load MIB button if (e.getActionCommand().equals("Load MIB")) { JFileChooser filechooser = new JFileChooser(); filechooser.showDialog(mibtree, "open"); try { mibtree.addMib(filechooser.getSelectedFile().toString()); } catch (Exception ex) { } } // if the user presses the unload mib button else if (e.getActionCommand().equals("Unload MIB")) { try { mibtree.deleteMib(mibtree.getSelectedMibModule().getName().toString()); } catch (Exception ex) { } } // if the user selects a leaf node and presses the description button else if (e.getActionCommand().equals("Description")) { textfield.setText("Syntax:"+mibtree.getSelectedMibNode().getSyntax() "\n"+"Access:"+mibtree.getSelectedMibNode().printAccess()+"\n"+ "Status:"+mibtree.getSelectedMibNode().getStatus()+"\n"+ "Reference:"+mibtree.getSelectedMibNode().getReference()+"\n"+ "OID:"+mibtree.getSelectedMibNode().getNumberedOIDString()+"\n"+ "Node:"+mibtree.getSelectedMibNode().getOIDString()+"\n"+ "Description:"+mibtree.getSelectedMibNode().getDescription()+"\n"); } // if the user presses the clear button else if (e.getActionCommand().equals("Clear")) { textfield.setText(""); } } Now, we can compile the source and view the results. The releaseResources() method of SnmpTarget class can be called to close the sessions. You can build similar applications effortlessly.
AdventNet, Inc.
379
Refer the source code for SnmpMibTree present in <tutorials/beans_ui_api/SnmpMibTree.java> for more information.
AdventNet, Inc.
380
Refer the source code for SnmpMibBrowser present in <tutorials/beans_ui_api/SnmpMibBrowser.java> for more information.
AdventNet, Inc.
381
AdventNet, Inc.
382
For this, the MIB file has to be loaded first in the MibOperations class. The getMibNode() is available both in MibOperations and MibModule class. If the methods in MibOperations are used, they are applicable for the node in all the MIBs loaded in the application. If the methods in the MibModule class are used, they are restricted to that particular module. Therefore, for better performance, it is recommended to use mibmodule.getMibNode(). The MibNode class has methods to get all the details about a MIB variable. We can get information about the selected MibNode, such as its syntax, OID, description, etc. System.out.println("Syntax:"+node.getSyntax()+"\n"+ "Access:"+node.printAccess()+"\n"+ "Status:"+node.getStatus()+"\n"+ "Reference:"+node.getReference()+"\n"+ "OID:"+node.getNumberedOIDString()+"\n"+ "Node:"+node.getOIDString()+"\n"+ "Description:"+node.getDescription()+"\n"); We can also use the method toTagString() to get the node information. Now, we can compile the program and view the result. Ensure that you provide the correct MIB file name and the proper OID in the command line. You can build similar applications effortlessly. Refer the source code of the following examples for more information. Tutorial Tutorial for getting MibNode information Command line example for getting MibNode information Available In <tutorials/mibs_api/MibNodeInfo.java> <examples/low_level_api_examples/mibapps/mibnodeinfo.java>
AdventNet, Inc.
383
Other Tutorials
Graphs with LineGraphBean Address and Name Lookup SAS as an Application SAS as Part of an Application
This section contains tutorials that explain the usage of the Graph beans in plotting the values of the variables in the remote agent. It also contains tutorials on the usage of sas package in developing applets and custom extensions that you can make to SAS.
AdventNet, Inc.
384
In this example, we use the LineGraphBean component. We need to import the com.adventnet.snmp.beans and com.adventnet.snmp.ui packages along with JDK packages. import import import import javax.swing.*; java.awt.event.*; com.adventnet.snmp.beans.*; com.adventnet.snmp.ui.*;
We will define the class and the static main function required for the Java applications. We implement the ResultListener interface which listens for the SNMP responses. We also instantiate all the Java beans components we use. The PropertySettings bean is used to set properties of other beans. Refer Tutorial Example on GET, GET NEXT (UI). public class SnmpGraph implements ResultListener { SnmpPoller poller = new SnmpPoller(); PropertySettings pptysettings = new PropertySettings(); LineGraphBean graph = new LineGraphBean(); public static void main(String args[]) { Now, we set some parameters for the SnmpPoller bean. poller.setTargetHost("localhost"); // can be changed using property settings bean poller.setObjectID(".1.3.6.1.2.1.4.3.0"); // plots iplnReceives from RFC-1213-MIB We need to add VetoableChangeListener to the PropertySettings bean and register a listener to receive the events from this bean. We register the SnmpPoller bean so that it is notified of any changes in the Property Settings bean and updated accordingly. pptysettings.addVetoableChangeListener(poller);
AdventNet, Inc.
385
Now, we add ResultListener to SnmpPoller for ResultEvents. poller.addResultListener(graph> Now, we implement setResult() of the Result Listener interface so that we get the following response. public void setNumericResult(long l) { } public void setResult(ResultEvent result) { //plot the results in the graph try try { graph.setResult(result.getNumericValue()); } catch (DataException de) { System.out.println("Error in getting agent data: "+ de + result.getErrorString()); } } public void setStringResult(String s){ } Now, we can compile the source and view the results. The releaseResources() method of SnmpTarget class can be called to close the sessions. You can build similar applications effortlessly. For example, you can use BarGraphBean instead of LineGraphBean. The screenshot of this tutorial example program is as follows.
Refer the source code of the following examples for more information. Tutorial Tutorial for using LineGraphBean Tutorial for using BarGraphBean Comprehensive example on using LineGraphBean Available In <tutorials/beans_ui_api/SnmpGraph.java> <tutorials/beans_ui_api/SnmpBarGraph.java> <examples/uiapplications/lineGraphDemo.java>
AdventNet, Inc.
386
2. Define the required class and the static main function. public class saslookup extends Applet implements ActionListener { 3. Instantiate the SnmpAPI, SnmpSession, SASClient classes and other UI components. SnmpAPI api; SnmpSession session; SASClient sasclient; TextArea text; TextField nameField, addressField, timeoutField; Button nameButton, addressButton; 4. Construct the SASClient instance. try { sasclient = new SASClient(this, false); } catch(SnmpException se) { text.append("Error : " + se.getMessage() + "\n"); } //SASClient is null if not connected to SAServer if(sasclient == null) { addressButton.setEnabled(false); addressButton.setEnabled(false); } 5. Include the code to perform lookups. The getHostAddress() and the getHostName() methods available in SASClient class maps IP address and host names. The getHostAddress() function resolves the host name to a dotted IP address with the help of SAS. The getHostName() method maps the dotted IP address to a fully qualified internet host name. if(e.getActionCommand().equals("Address Lookup")) { int timeout = 0; // other codes go here try { String address = sasclient.getHostAddress(nameField.getText(), timeout); } catch (Exception ex) { } } else if(e.getActionCommand().equals("Name Lookup"))
AdventNet, Inc.
387
{ int timeout = 0; try { String name = sasclient.getHostName(addressField.getText(), timeout); } catch (Exception ex) { } } Refer the source code for saslookup present in <examples/sasapps/saslookup.java> for more information. Now, we can compile the source and load and view the applet. Refer GET, GETNEXT for a discussion on the different ways of loading the applet and different HTML files we need to create.
AdventNet, Inc.
388
SAS as an Application
In this tutorial, we discuss how SAS can be used by a standalone application so that it can act as a proxy for SNMP communication. Manager applications can communicate with this application which in turn communicates with the actual devices and passes the results to the manager applications. We need to use the SASAppletStub class in the snmp2 package. This class provides the implementation of the AppletStub methods to plug into applet to simulate applet behavior. This class is used to pass the "applet behavior" to the SnmpSession's open() method while using client applications (instead of applets) with SAS. We also make use of the sasappclient applet provided in the "sasapps" directory. Refer the source code for sasappclient present in <examples/sasapps/sasappclient.java> for more information. This applet invokes the SASClient's userSyncSend() method to send data to the server to perform some operation. It receives the response data and prints it. It sends and receives the data continuously. The example which we develop shows how applications can use the sasappclient file by plugging in their own applet stub. It instantiates the sasappclient object, sets the user-defined AppletStub stub into it. We need to import the following packages. import import import import import com.adventnet.management.transport.*; com.adventnet.snmp.snmp2.*; javax.swing.*; java.awt.event.*; java.net.*;
We define the required class and the static main function. public class sastest extends JFrame { sastest() { super("SAS Application"); } public static void main (String[] args) { Instantiate the sasappclient applet. sastest testObj = new sastest(); final sasappclient obj = new sasappclient(); We instantiate the SASApplet stub class, plug it into the applet and set various parameters, such as host name, port, code base and document base. //Create the Applet stub & plug it into the Applet SASAppletStub sasStub = new SASAppletStub(); //set the transport provider sasStub.setParameter("TRANSPORT_PROVIDER", "com.adventnet.management.transport.TcpClientTransportImpl"); //localhost can be replaced by any host name sasStub.setParameter("HOST","localhost"); //set the port parameter to the port in which SAServer is
AdventNet, Inc.
389
listening. sasStub.setParameter("PORT","1575"); sasStub.setParameter("CODEBASE", "http://localhost:8282/"); sasStub.setParameter("DOCUMENTBASE", "http://localhost:8282/"); try { URL codebase = new URL("http://localhost:8282/"); sasStub.setCodeBase(codebase); sasStub.setDocumentBase(codebase); } catch (Exception e) { } obj.setStub(sasStub);\ Now, we can start the applet. // Start the Applet obj.init(); obj.start(); If we execute the application, we can see that the application uses SAS for its communication. Similarly, any application that performs SNMP operations can be built. Refer the source code of the following examples for more information. Tutorial Example for the standalone application which uses SAS for communication SNMP GET application which uses SAS for communication Available In <examples/sasapps/sasapplication.java> <tutorials/sas_api/snmpget.java>
AdventNet, Inc.
390
2. Define the required class and the static main function. public class SASTestAppn implements ActionListener { 3. Instantiate SAServer and the necessary UI components. JTextArea textfield = new JTextArea(); JButton setbutton = new JButton(); SAServer sasserver; 4. The SAServer thread has to be started to start SAS. The SAS thread is started when the user clicks the "start" button. if (e.getActionCommand().equals("Start")) { sasserver = new SAServer(); sasserver.setFileOutput(true); sasserver.start(); textfield.setText("SAS Server is running now ......."); setbutton.setText("Stop"); } 6. When the user clicks the "stop" button, the SAS thread stops. else if (e.getActionCommand().equals("Stop")) { sasserver.close(); textfield.setText("Press the start button to start SAS Server ......."); setbutton.setText("Start"); } Now, we can compile the source and run the application.
AdventNet, Inc.
391
Refer the source code for SASTestAppn present in <tutorials/sas_api/SASTestAppn.java> for more information.
AdventNet, Inc.
392
Complete Example
In this tutorial example, we have put together some of the examples which we have done so far and created a crude mini MibBrowser. You can add your own functionality to further customize it. You can also include the trap and table-related components. The screenshot of this tutorial example program is as follows.
Refer the source code for CompleteExample present in <tutorials/beans_ui_api/CompleteExample.java> for more information. MibBrowser Bean includes all the functions, which we have discussed so far.
AdventNet, Inc.
393
Performance Metrics
Performance Numbers for Modules Performance Numbers for MIB Loading Options Performance Numbers for Traps
This section gives the performance numbers for the various modules and traps.
AdventNet, Inc.
394
High-Level API
Type Synchronous Asynchronous v1 (Requests/second) 3844 4655 v2c (Requests/second) 3833 4772
Low-Level API
Type Synchronous Asynchronous v1 (Requests/second) 4699 5601 v2c (Requests/second) 4879 5523
AdventNet, Inc.
395
The loading time (in milliseconds) of some of the standard MIBs using the different loading options of the AdventNet SNMP API is given below. Database Mode Compiled MIBs Mode Overwriting Normal Loading Overwriting Loading Mode/MIB into Mode from the the from the the database cmi file cmi file database RFC1213789 2460 501 529 225 MIB IF-MIB 667 4280 322 780 330 RMON21803 14192 1313 1518 495 MIB Serialized MIB Overwriting Loading the from the serialized serialized file file 775 1080 1841 787 1043 1770
Note: All statistical data provided above is an average and they may vary according to the memory and CPU usage of the machine concerned and the prevailing current network traffic.
AdventNet, Inc.
396
All the traps were received by the TrapReceiver without any loss. All traps were SNMPv1 traps. Note: All statistical data provided above is an average and they may vary according to the memory and CPU usage of the machine concerned and the prevailing current network traffic.
AdventNet, Inc.
397
Migration Guide
Migration from 3.x to 4.0 Migration from 2.x to 4.0
This section details the changes that has been done in AdventNet SNMP API 4 with respect to the previous releases. Developers upgrading from the earlier releases (2.x and 3.x series) are strongly advised to go through the respective sections.
AdventNet, Inc.
398
This section describes the changes that have been made to the high-level API, low-level API, and MIBs API between the 3.x release to 4.0 release.
AdventNet, Inc.
399
getMibModules() getMibModuleNames()
MibOperations MibOperationsImpl
In the case of any exception such as "No such object in this MIB", "No such instance in this MIB" and "End of Mib View", these values were returned in getErrorCode() method. Since these are exception, these values will be returned in a new method getExceptionCode(). In this case, the errorCode value will be zero. Similarly, when errorCode is set, getExceptionCode() returns zero. If a GET operation is performed by setting an invalid String OID using SnmpTarget, the request will not be sent. The error message would be set as "OID Not Specified".
AdventNet, Inc.
400
Low-Level API
The API changes in SnmpAPI are listed below. S.No. 1 2 3 4 Deprecated Method/Variable BITSTRING NSAP Standard_Prefix UINTEGER32 Comment This variable has been deprecated in SNMPv2. This variable has been deprecated in SNMPv2. This should not be a public string variable. Variables should not be public. Instead, use the setOIDPrefix(SnmpOID oid) and getOIDPrefix() methods. This variable has been deprecated in SNMP.
The API changes in SnmpPDU are listed below. S.No. Deprecated Method/Variable Comment SnmpPDU should know only the SNMP variables and protocol-independent variables. Here, the InetAddress is specific to UDP and therefore this method is deprecated. Use the following instead. UDPProtocolOptions opt = (UDPProtocolOptions) SnmpPDU.getProtocolOptions(); InetAddress address = opt.getRemoteAddress(); SnmpPDU should know only the SNMP variables and protocol-independent variables. Here, the host is specific to UDP and therefore this method is deprecated. Use the following instead. UDPProtocolOptions opt = (UDPProtocolOptions) SnmpPDU.getProtocolOptions(); String remoteHost = opt.getRemoteHost(); SnmpPDU should know only the SNMP variables and protocol-independent variables. Here, the port is specific to UDP and therefore this method is deprecated. Use the following instead. UDPProtocolOptions opt = (UDPProtocolOptions) SnmpPDU.getProtocolOptions(); int remotePort = opt.getRemotePort(); SnmpPDU should know only the SNMP variables and protocol-independent variables. Here, the InetAddress is specific to UDP and therefore this method is deprecated. Use the following instead. UDPProtocolOptions opt = (UDPProtocolOptions) SnmpPDU.getProtocolOptions(); opt.setRemoteAddress(address); Lookup is not done.
getAddress()
getRemoteHost()
getRemotePort()
setAddress(InetAddress address)
setDNSLookup(boolean lookup)
SnmpPDU should know only the SNMP variables and setRemoteHost(java.lang.String protocol-independent variables. Here, the host is host) specific to UDP and therefore this method is deprecated.
AdventNet, Inc.
401
setRemotePort(int port)
Comment Use the following instead. UDPProtocolOptions opt = (UDPProtocolOptions)SnmpPDU.getProtocolOptions(); opt.setRemoteHost(host); SnmpPDU should know only the SNMP variables and protocol-independent variables. Here, the port is specific to UDP and therefore this method is deprecated. Use the following instead. UDPProtocolOptions opt = (UDPProtocolOptions)SnmpPDU.getProtocolOptions(); opt.setRemotePort(port);
The API changes in SnmpSession are listed below. S.No. 1 IP Deprecated Method/Variable Comment This is a static constant for identifying IP. This is not required because all SNMP communications are through a single transport provider. This is a static constant for transport provider framework. This is not required because all SNMP communications are through a single transport provider. SnmpSession is used for any type of SNMP communication and therefore methods specific to get or set operations are not required. Use the following instead. SnmpPDU pdu = new SnmpPDU(); pdu.addNull(oid); pdu.setCommand(SnmpAPI.GET_REQ_MSG); SnmpPDU response_pdu = SnmpSession.syncSend(pdu); SnmpVar var = null; if(response_pdu != null) { var = response_pdu.getVariable(0); } SnmpSession is used for any type of SNMP communication and therefore methods specific to get or set operations are not required. Use the following instead. SnmpPDU pdu = new SnmpPDU(); pdu.addNull(oid); pdu.setCommand(SnmpAPI.GET_REQ_MSG); SnmpPDU response_pdu = snmpSession.syncSend(pdu); SnmpVar var = null; if(response_pdu != null) { var = response_pdu.getVariable(0); } SnmpSession should know only the SNMP variables and protocol-independent variables. Here, the address is specific to UDP and therefore this method is deprecated. Use the following instead. UDPProtocolOptions opt = (UDPProtocolOptions) snmpSession.getProtocolOptions(); String[] local_address = opt.getLocalAddresses();
TRANSPORT_PROVIDER
get(SnmpOID oid)
get(String oidString)
getLocalAddresses()
AdventNet, Inc.
402
S.No.
Deprecated Method/Variable
Comment SnmpSession should know only the SNMP variables and protocol-independent variables. Here, the port is specific to UDP and therefore this method is deprecated. Use the following instead. UDPProtocolOptions opt = (UDPProtocolOptions) snmpSession.getProtocolOptions(); int local_port = opt.getLocalPort(); SnmpSession is used for any type of SNMP communication and therefore methods specific to get or set operations are not required. Use the following instead. SnmpPDU pdu = new SnmpPDU(); pdu.addNull(oid); pdu.setCommand(SnmpAPI.GETNEXT_REQ_MSG); SnmpPDU response_pdu = snmpSession.syncSend(pdu); SnmpVar var = null; if(response_pdu != null) { var = response_pdu.getVariable(0); } SnmpSession is used for any type of SNMP communication and therefore methods specific to get or set operations are not required. Use the following instead. SnmpPDU pdu = new SnmpPDU(); pdu.addNull(new SnmpOID(oidString)); pdu.setCommand(SnmpAPI.GETNEXT_REQ_MSG); SnmpPDU response_pdu = snmpSession.syncSend(pdu); SnmpVar var = null; if(response_pdu != null) { var = response_pdu.getVariable(0); } SnmpSession should know only the SNMP variables and protocol-independent variables. Here, the address is specific to UDP and therefore this method is deprecated. Use the following instead. UDPProtocolOptions opt = (UDPProtocolOptions) SnmpSession.getProtocolOptions(); opt.getRemoteHost(); This returns the protocol associated with the session object. This is not required because all SNMP communications are through a single transport provider. This returns the remote port on the peer to which the session communicates. This is not required because all SNMP communications are through a single transport provider. This method is not required because all SNMP communications are through a single transport provider. Use the following instead. SASProtocolOptions opt = (SASProtocolOptions)SnmpSession.getProtocolOptions(); SASClient sasclient = opt.getSASClient();
int getLocalPort()
getnext(SnmpOID oid)
getnext(String oidString)
getPeername()
10
getProtocol()
11
getRemotePort()
12
getSASClient()
AdventNet, Inc.
403
S.No.
Deprecated Method/Variable
Comment This method is not required because all SNMP communications are through a single transport provider. Use the following instead. SASProtocolOptions opt = (SASProtocolOptions)snmpSession.getProtocolOptions(); int sasprotocol = opt.getProtocol(); This method is no longer supported. Use the following instead. int snmpClientsSize = (snmpSession.getSnmpClients()).size(); At present, the open(Applet) method throws an SnmpException if connection to the SAServer fails. When such an exception is received, the user can decide to call the open(void) method. This method is not required because all SNMP communications are through a single transport provider. Use the following instead. SnmpAPI api = new SnmpAPI(); SnmpSession ses = new SnmpSession(api); SASProtocolOptions opt = new SASProtocolOptions(); opt.setApplet(applet); ses.setProtocolOptions(opt); ses.open(); SnmpSession is used for any type of SNMP communication and therefore methods specific to get or set operations are not required. Use the following instead. SnmpPDU pdu = new SnmpPDU(); SnmpVarBind varbind = new SnmpVarBind(oid, var); pdu.addVariableBinding(varbind); pdu.setCommand(SnmpAPI.SET_REQ_MSG); SnmpPDU response_pdu = SnmpSession.syncSend(pdu); SnmpVar response_var = null; if(response_pdu != null) { response_var = response_pdu.getVariable(0); } SnmpSession is used for any type of SNMP communication and therefore methods specific to get or set operations are not required. Use the following instead. SnmpPDU pdu = new SnmpPDU(); SnmpVar variable = SnmpVar.createVariable(setString, type); SnmpOID oid = new SnmpOID(oidString); SnmpVarBind varbind = new SnmpVarBind(oid, variable); pdu.addVariableBinding(varbind); pdu.setCommand(SnmpAPI.SET_REQ_MSG); SnmpPDU response_pdu = snmpSession.syncSend(pdu); SnmpVar var = null; if(response_pdu != null) { var = response_pdu.getVariable(0); }
13
getSASProtocol()
14
getSnmpClientsSize()
15
getStartLocalPort()
16
open(Applet applet)
17
18
AdventNet, Inc.
404
S.No.
Deprecated Method/Variable
Comment LocalAddresses should be specified only through a ProtocolOptions because all SNMP communications are through a single transport provider. Use the following instead UDPProtocolOptions opt = (UDPProtocolOptions)snmpSession.getProtocolOptions(); opt.setLocalAddresses(local_addrs); LocalPort should be specified only through a ProtocolOptions because all SNMP communications are through a single transport provider. UDPProtocolOptions opt = (UDPProtocolOptions)snmpSession.getProtocolOptions(); opt.setLocalPort(local_port); SnmpSession should know only the SNMP variables and protocol-independent variables. Here, the peer name is specific to UDP and therefore this method is deprecated. Use the following instead. UDPProtocolOptions opt = (UDPProtocolOptions)snmpSession.getProtocolOptions(); opt.setRemoteHost(peername); This method is not required because all SNMP communications are through a single transport provider. SnmpSession should know only the SNMP variables and protocol-independent variables. Here, the port is specific to UDP and therefore this method is deprecated. Use the following instead. UDPProtocolOptions opt = (UDPProtocolOptions)snmpSession.getProtocolOptions(); opt.setRemotePort(port); SASProtocol should be specified only through a ProtocolOptions because all SNMP communications are through a single transport provider. Use the following instead. SASProtocolOptions opt = new SASProtocolOptions(); opt.setApplet(applet); opt.setProtocol(SASClient.TCP_PROTOCOL); //or SASClient.HTTP_PROTOCOL SnmpSession.setProtocolOptions(opt); SnmpSession.open(); This method is not required because all SNMP communications are through a single transport provider. At present, the open(Applet) method throws an SnmpException if connection to the SAServer fails. When such an exception is received, the user can decide to call the open(void) method.
19
setLocalAddresses(String[] local_addrs)
20
setLocalPort(int local_port)
21
setPeername(String peername)
22
setProtocol(int protocol)
23
setRemotePort(int port)
24
setSASProtocol(int prot)
25
26
The traps will not be enqueued in the response list of SnmpSession. Therefore, the receive(int reqid) method of SnmpSession will not receive them. The SnmpClient interface should be implemented and added to the SnmpSession for receiving the traps. Previously, in the Hashtable returned by the method getSnmpClientsWithID in the class SnmpSession, the key clientID was an String object. Now the key clientID is put in the Hashtable as an Integer object.
AdventNet, Inc.
405
The API changes in MibNode are listed below. S.No. 1 2 3 4 Deprecated Method/Variable getRevision() getRevdescription() getObjectNames() getFilename() Comment Use the getRevisions() method instead. Use the getRevdescriptions() method instead. Use the getObjects() method instead. Use the getFileName() method instead.
The API changes in AgentCapabilitiesModule are listed below. S.No. 1 2 3 4 5 6 7 Deprecated Method/Variable getVariation() Comment
Use the getACVariation() method instead. Use the getSyntax() method in the ACVariation class getSyntax() instead. Use the getWriteSyntax() method in the ACVariation getWriteSyntax() class instead. Use the getAccess() method in the ACVariation class getAccess() instead. Use the getCreationObjects() method in the ACVariation getCreationRequires() class instead. Use the getDefVal() method in the ACVariation class getDefval() instead. Use the getDescription() method in the ACVariation class getVariationDescription() instead.
AdventNet, Inc.
406
This section describes the changes that have been made to the low-level API and MIBs API between the 2.x release to 4.0 release.
AdventNet, Inc.
407
The API changes in SnmpPDU are listed below. S.No. Deprecated Method/Variable Comment SnmpPDU should know only the SNMP variables and protocol-independent variables. Here, the InetAddress is specific to UDP and therefore this method is deprecated. Use the following instead. UDPProtocolOptions opt = (UDPProtocolOptions) SnmpPDU.getProtocolOptions(); InetAddress address = opt.getRemoteAddress(); SnmpPDU should know only the SNMP variables and protocol-independent variables. Here, the host is specific to UDP and therefore this method is deprecated. Use the following instead. UDPProtocolOptions opt = (UDPProtocolOptions) SnmpPDU.getProtocolOptions(); String remoteHost = opt.getRemoteHost(); SnmpPDU should know only the SNMP variables and protocol-independent variables. Here, the port is specific to UDP and therefore this method is deprecated. Use the following instead. UDPProtocolOptions opt = (UDPProtocolOptions) SnmpPDU.getProtocolOptions(); int remotePort = opt.getRemotePort(); SnmpPDU should know only the SNMP variables and protocol-independent variables. Here, the InetAddress is specific to UDP and therefore this method is deprecated. Use the following instead. UDPProtocolOptions opt = (UDPProtocolOptions) SnmpPDU.getProtocolOptions(); opt.setRemoteAddress(address); No lookup is done.
getAddress()
getRemoteHost()
getRemotePort()
setAddress(InetAddress address)
setDNSLookup(boolean lookup)
SnmpPDU should know only the SNMP variables and setRemoteHost(java.lang.String protocol-independent variables. Here, the host is specific to UDP and therefore this method is host) deprecated.
AdventNet, Inc.
408
setRemotePort(int port)
Comment Use the following instead. UDPProtocolOptions opt = (UDPProtocolOptions)SnmpPDU.getProtocolOptions(); opt.setRemoteHost(host); SnmpPDU should know only the SNMP variables and protocol-independent variables. Here, the port is specific to UDP and therefore this method is deprecated. Use the following instead. UDPProtocolOptions opt = (UDPProtocolOptions)SnmpPDU.getProtocolOptions(); opt.setRemotePort(port);
The API changes in SnmpSession are listed below. S.No. 1 IP Deprecated Method/Variable Comment This is a static constant for identifying IP. This is not required because all SNMP communications are through a single transport provider. This is a static constant for transport provider framework. This is not required because all SNMP communications are through a single transport provider. SnmpSession is used for any type of SNMP communication and therefore methods specific to get or set operations are not required. Use the following instead. SnmpPDU pdu = new SnmpPDU(); pdu.addNull(oid); pdu.setCommand(SnmpAPI.GET_REQ_MSG); SnmpPDU response_pdu = SnmpSession.syncSend(pdu); SnmpVar var = null; if(response_pdu != null) { var = response_pdu.getVariable(0); } SnmpSession is used for any type of SNMP communication and therefore methods specific to get or set operations are not required. Use the following instead. SnmpPDU pdu = new SnmpPDU(); pdu.addNull(oid); pdu.setCommand(SnmpAPI.GET_REQ_MSG); SnmpPDU response_pdu = snmpSession.syncSend(pdu); SnmpVar var = null; if(response_pdu != null) { var = response_pdu.getVariable(0); } SnmpSession should know only the SNMP variables and protocol-independent variables. Here, the address is specific to UDP and therefore this method is deprecated. Use the following instead. UDPProtocolOptions opt = (UDPProtocolOptions) snmpSession.getProtocolOptions(); String[] local_address = opt.getLocalAddresses();
TRANSPORT_PROVIDER
get(SnmpOID oid)
get(String oidString)
getLocalAddresses()
AdventNet, Inc.
409
S.No.
Deprecated Method/Variable
Comment SnmpSession should know only the SNMP variables and protocol-independent variables. Here, the port is specific to UDP and therefore this method is deprecated. Use the following instead. UDPProtocolOptions opt = (UDPProtocolOptions) snmpSession.getProtocolOptions(); int local_port = opt.getLocalPort(); SnmpSession is used for any type of SNMP communication and therefore methods specific to get or set operations are not required. Use the following instead. SnmpPDU pdu = new SnmpPDU(); pdu.addNull(oid); pdu.setCommand(SnmpAPI.GETNEXT_REQ_MSG); SnmpPDU response_pdu = snmpSession.syncSend(pdu); SnmpVar var = null; if(response_pdu != null) { var = response_pdu.getVariable(0); } SnmpSession is used for any type of SNMP communication and therefore methods specific to get or set operations are not required. Use the following instead. SnmpPDU pdu = new SnmpPDU(); pdu.addNull(new SnmpOID(oidString)); pdu.setCommand(SnmpAPI.GETNEXT_REQ_MSG); SnmpPDU response_pdu = snmpSession.syncSend(pdu); SnmpVar var = null; if(response_pdu != null) { var = response_pdu.getVariable(0); } SnmpSession should know only the SNMP variables and protocol-independent variables. Here, the address is specific to UDP and therefore this method is deprecated. Use the following instead. UDPProtocolOptions opt = (UDPProtocolOptions) SnmpSession.getProtocolOptions(); opt.getRemoteHost(); This returns the protocol associated with the session object. This is not required because all SNMP communications are through a single transport provider. This returns the remote port on the peer to which the session communicates. This is not required because all SNMP communications are through a single transport provider. This method is not required because all SNMP communications are through a single transport provider. Use the following instead. SASProtocolOptions opt = (SASProtocolOptions)SnmpSession.getProtocolOptions(); SASClient sasclient = opt.getSASClient();
int getLocalPort()
getnext(SnmpOID oid)
getnext(String oidString)
getPeername()
10
getProtocol()
11
getRemotePort()
12
getSASClient()
AdventNet, Inc.
410
S.No.
Deprecated Method/Variable
Comment This method is not required because all SNMP communications are through a single transport provider. Use the following instead. SASProtocolOptions opt = (SASProtocolOptions)snmpSession.getProtocolOptions(); int sasprotocol = opt.getProtocol(); This method is no longer supported. Use the following instead. int snmpClientsSize = (snmpSession.getSnmpClients()).size(); At present, the open(Applet) method throws an SnmpException if connection to the SAServer fails. When such an exception is received, the user can decide to call the open(void) method. This method is not required because all SNMP communications are through a single transport provider. Use the following instead. SnmpAPI api = new SnmpAPI(); SnmpSession ses = new SnmpSession(api); SASProtocolOptions opt = new SASProtocolOptions(); opt.setApplet(applet); ses.setProtocolOptions(opt); ses.open(); SnmpSession is used for any type of SNMP communication and therefore methods specific to get or set operations are not required. Use the following instead. SnmpPDU pdu = new SnmpPDU(); SnmpVarBind varbind = new SnmpVarBind(oid, var); pdu.addVariableBinding(varbind); pdu.setCommand(SnmpAPI.SET_REQ_MSG); SnmpPDU response_pdu = SnmpSession.syncSend(pdu); SnmpVar response_var = null; if(response_pdu != null) { response_var = response_pdu.getVariable(0); } SnmpSession is used for any type of SNMP communication and therefore methods specific to get or set operations are not required. Use the following instead. SnmpPDU pdu = new SnmpPDU(); SnmpVar variable = SnmpVar.createVariable(setString, type); SnmpOID oid = new SnmpOID(oidString); SnmpVarBind varbind = new SnmpVarBind(oid, variable); pdu.addVariableBinding(varbind); pdu.setCommand(SnmpAPI.SET_REQ_MSG); SnmpPDU response_pdu = snmpSession.syncSend(pdu); SnmpVar var = null; if(response_pdu != null) { var = response_pdu.getVariable(0); }
13
getSASProtocol()
14
getSnmpClientsSize()
15
getStartLocalPort()
16
open(Applet applet)
17
18
AdventNet, Inc.
411
S.No.
Deprecated Method/Variable
Comment LocalAddresses should be specified only through a ProtocolOptions because all SNMP communications are through a single transport provider. Use the following instead UDPProtocolOptions opt = (UDPProtocolOptions)snmpSession.getProtocolOptions(); opt.setLocalAddresses(local_addrs); LocalPort should be specified only through a ProtocolOptions because all SNMP communications are through a single transport provider. UDPProtocolOptions opt = (UDPProtocolOptions)snmpSession.getProtocolOptions(); opt.setLocalPort(local_port); SnmpSession should know only the SNMP variables and protocol-independent variables. Here, the peer name is specific to UDP and therefore this method is deprecated. Use the following instead. UDPProtocolOptions opt = (UDPProtocolOptions)snmpSession.getProtocolOptions(); opt.setRemoteHost(peername); This method is not required because all SNMP communications are through a single transport provider. SnmpSession should know only the SNMP variables and protocol-independent variables. Here, the port is specific to UDP and therefore this method is deprecated. Use the following instead. UDPProtocolOptions opt = (UDPProtocolOptions)snmpSession.getProtocolOptions(); opt.setRemotePort(port); SASProtocol should be specified only through a ProtocolOptions because all SNMP communications are through a single transport provider. Use the following instead. SASProtocolOptions opt = new SASProtocolOptions(); opt.setApplet(applet); opt.setProtocol(SASClient.TCP_PROTOCOL); //or SASClient.HTTP_PROTOCOL SnmpSession.setProtocolOptions(opt); SnmpSession.open(); This method is not required because all SNMP communications are through a single transport provider. At present, the open(Applet) method throws an SnmpException if connection to the SAServer fails. When such an exception is received, the user can decide to call the open(void) method.
19
setLocalAddresses(String[] local_addrs)
20
setLocalPort(int local_port)
21
setPeername(String peername)
22
setProtocol(int protocol)
23
setRemotePort(int port)
24
setSASProtocol(int prot)
25
26
AdventNet, Inc.
412
The API changes in MibNode are listed below. S.No. Deprecated Method/Variable 1 getRevision() 2 getRevdescription() 3 getObjectNames() 4 getFilename() Comment Use the getRevisions() method instead. Use the getRevdescriptions() method instead. Use the getObjects() method instead. Use the getFileName() method instead.
The API changes in AgentCapabilitiesModule are listed below. S.No. 1 2 3 4 5 6 7 Deprecated Method/Variable Comment Use the getACVariation() method instead. getVariation() Use the getSyntax() method in the ACVariation class getSyntax() instead. Use the getWriteSyntax() method in the ACVariation getWriteSyntax() class instead. Use the getAccess() method in the ACVariation class getAccess() instead. Use the getCreationObjects() method in the getCreationRequires() ACVariation class instead. Use the getDefVal() method in the ACVariation class getDefval() instead. Use the getDescription() method in the ACVariation getVariationDescription() class instead.
In this release we have introduced a new MibParser to parse the MIB file. In the earlier releases, both parsing the MIB and constructing the tree are done in the com.adventnet.snmp.mibs package itself. Now parsing of MIBs is done by the mibparser package and the tree is constructed in the mibs package. The mibparser package is not transparent to the user and it is used internally by the mibs package. As far as the public API is concerned, there is no change in API methods. Therefore, the existing applications using the mibs package will still work with the new changes in the mibs package. One key enhancement is the option of loading MIB files as compiled MIB files. The loading of compiled MIB files gives good performance when compared with the loading of the normal MIB file. Refer MIB Support API for more details. The following are the changes in MIB related operations due to new MibParser.
AdventNet, Inc.
413
1. All the modules defined in the import field should be present. Earlier even if imports, such as mib-2 from RFC1213-MIB failed, it loads the MIB after printing a warning message. Now it is mandatory that all the modules defined in the imports are present. 2. OID definitions such as the following will not work. newNode OBJECT IDENTIFIER ::= { ModuleName.nodeName 1} newNode OBJECT IDENTIFIER ::= { 1 3 6 .......} newNode OBJECT IDENTIFIER ::= { 1 } 3. Module name should not start with a lower case letter or number. 4. Enumeration label should not start with a number. 5. Since multiple roots are shown in the MibTree now, GET and GETNEXT operation from the MIB browser after selecting the module name will fail. You have to select the MIB node. 6. If the module contains multiple roots like iso and ccitt, then the getRootNode method in MibModule of release 2 will return an iso. Now the behaviour has been changed to return null. The method getRootNodes added in Release 3.1 can be used to get all the root nodes. 7. Methods such as getDefval(), getUnits(), getReference(), etc. which used to return null if it is not defined in the mib. Now it will return an empty string. 8. The start()method of the SnmpAPI class is invoked when the class is instantiated and therefore need not be explicitly called. 9. If the syntax of a node is a TextualConvention, say myTC, then myTC instanceof LeafSyntax which used to return true in the earlier releases, will return false now. But myTC instanceof MibTC will return true. Since MibTC extends LeafSyntax you can access all the methods available in LeafSyntax. In the LeafSyntax class in the mibs package, methods such as getName(), toString(), getDescription() were all returning the same information in the earlier releases. For example, a syntax of INTEGER with range (1 .. 200 | 400 .. 500) were returning INTEGER (1 .. 200 | 400 .. 500). In the Release 3.x, the getName() and toString() method will return only the name of the syntax ( i.e., INTEGER) and the getDescription() will return the syntax along with the range ( i.e., INTEGER ( 1 .. 200 | 400 .. 500 ) ) In the earlier releases, getDescription() in the MibTC class used to return the TC description. Now getDescription() returns the name of the MibTC along with the range. A new method getTCDescription() is added, which returns the description of the Textual Convention.
AdventNet, Inc.
414
FAQs
Beginners FAQs General Beans Components Low-Level API MIBs API SAS and Web Server EJB API RMI API CORBA API
AdventNet, Inc.
415
Beginners FAQs
1. What is AdventNet SNMP API? 2. What can I do with this product? 3. What operating systems does it run on? 4. How do I start using this package? 5. What do I need to start developing applications and applets in Java using the AdventNet SNMP package? 6. What are the platforms for which JDK is available? 7. How do I run the various example applications provided? 8. I am able to execute the example applications but I am not getting results. What should I do? 9. How do I view and use the various example applets? 10. Why do the applets fail to work in my browsers? 11. What is the difference between SNMPv1, SNMPv2c, and SNMPv3? 12. Which versions of SNMP are supported by AdventNet SNMP API? 13. What is new in SNMPv3? 14. I do not have access to an SNMPv3 agent, but I want to test the SNMPv3 features. What should I do? 1. What is AdventNet SNMP API? AdventNet SNMP API is a set of class libraries in Java for writing the network management applets and applications. 2. What can I do with this product? This package can be used to develop SNMP management applications to manage SNMPv1, SNMPv2c, and SNMPv3 agents and talk to agent systems using any of the three versions at the same time. 3. What operating systems does it run on? The product is developed in Java and therefore it is platform independent. You can use the product in any operating system with the JDK port of that particular OS. On our part, we have tested the product in the following platforms. Windows 95 Windows 98 Windows 2000 Windows NT RedHat Linux 6.x RedHat Linux 7.x RedHat Linux 8.x RedHat Linux Enterprise 4 Solaris 7 Solaris 8 Solaris 9 Solaris 10
AdventNet, Inc.
416
The JDK versions supported are 1.2 and above. However, MibBrowser will work only with JDK 1.2.2 and above. 4. How do I start using this package? AdventNet SNMP API distribution consists of the following. SNMP API - a set of class libraries in Java to build SNMP management applications. The product distribution also includes various example applications and applets. It provides a hierarchy of Java packages for SNMP, MIBs, beans, UI/Swing, RMI, CORBA, and EJB, which helps in developing various non-UI and UI applications. The com.adventnet.snmp.ui package provides a number of useful Bean components that can be used in developing management GUI applications. The MibBrowser application is one such application that is developed using this API library. 5. What do I need to start developing applications and applets in Java using the AdventNet SNMP package? You need the Java Developers Kit (JDK-1.1.6 and above) to develop applications and applets using this AdventNet SNMP package. In addition, you need to download and setup the AdventNet SNMP package classes. 6. What are the platforms for which JDK is available? JDK is available on a number of platforms, including Solaris, Windows 95, Windows 98, Windows NT, Windows 2000, MacOS, HP-UX, Linux, AIX, and OS/2 from different sources. You can also use one of the Java development tools, such as Symantec Cafe, JBuilder, MS Visual J++, etc. which provides the JDK functionality. 7. How do I run the various example applications provided? The product distribution includes various example applications in the following directories. examples/applications/ - contains examples which uses Beans package. examples/uiapplications/ - contains examples which uses ui package. examples/low_level_api_examples/snmpapps/ - contains examples which uses snmp2 package, with UDP as the underlying protocol. examples/low_level_api_examples/mibapps/ - contains examples which uses mibs package. examples/low_level_api_examples/tcpapps/ - contains examples which uses snmp2 package, with TCP as the underlying protocol. examples/sasapps/ - contains examples which uses sas package. examples/httpapps/ - contains examples which uses HTTP tunelling. examples/rmiclient/ - contains examples which uses rmi package. examples/corbaclient/ - contains examples which uses corba package. examples/ejbclient/- contains examples which uses ejb package.
Examples include applications, such as snmpget, and snmpgetnext. Multiple versions of these applications are available in different directories. You can use them to query information from the SNMP agents on your network. All the applications that are used to query an agent have identical syntax. In general, all the command line tools gives help information when you type the following. java command-name
AdventNet, Inc.
417
For example, to get help information on the command snmpgetnext, type: java snmpgetnext To compile or execute the application, you have to set the CLASSPATH to the current directory and the classes directory. You have to run setenv.bat (Windows) or setenv.sh (Unix) to set the JAVA_HOME and CLASSPATH environment variables. 8. I am able to execute the example applications but I am not getting results. What should I do? If you get a timeout error after executing the application, the remote host given by you might not have an SNMP agent running on it. The agent should be running on the system on which you are querying. Therefore, install an SNMP agent in the machine or try on some other host which has the SNMP agent. Your network administrator might know more about this. In general, routers, ethernet switches, and network printers have the SNMP agent. You can try querying these devices. 9. How do I view and use the various example applets? You need a Java-enabled web browser, such as Netscape Navigator or Internet Explorer or the JDK appletviewer. Sun's Java plug-in is required to test/view the applets which use swing or JFC components. The standard Netscape 4.x or IE 4.x browsers do not support JFC classes. Applets which do not use swing components can be tested using standard web browsers. 10. Why do the applets fail to work in my browsers? If you want to load the Java classes and applet HTML file locally from your own file system, you need to invoke your web browser with your CLASSPATH set. Otherwise, the applet fails. The applet has to be loaded from the code base in your HTML file and this code base directory should be in the CLASSPATH. If you want to load the classes over the network, Netscape Navigator and Internet Explorer do not allow any communication except to the host from where you have loaded your applet. In order to get this to work, you need to use the SNMP Applet Server (SAS) on your applet host (web server) or use HTTP tunneling. 11. What is the difference between SNMPv1, SNMPv2c, and SNMPv3? SNMPv1 is the original protocol and framework which is described in RFCs 1155 and 1157. SNMPv2c is the revised protocol which includes improvements to SNMPv1 in the areas of protocol packet types, transport mappings, and MIB structure elements. However, it uses the existing SNMPv1 administration structure ("community-based" and hence SNMPv2c). SNMPv3 defines the secure version of the SNMP. SNMPv3 also facilitates remote configuration of the SNMP entities which makes remote administration of SNMP entities a much simpler task. 12. Which versions of SNMP are supported by AdventNet SNMP API? The AdventNet SNMP API distribution supports v1 ,v2c, and v3 versions of SNMP. The communication and MIB portions of the AdventNet SNMP API conform to the following Internet RFC specifications. SNMPv1 - RFC 1155 and RFC 1157 SNMPv2c - RFC 1901 and RFC 1907 SNMPv3 - RFC 2571 and RFC 2572 SNMPv3 User-based Security Model (USM) - RFC 2574 SNMPv3 View-based Access Control Model (VACM) - RFC 2575 Co-existence between SNMPv1, SNMPv2c, SNMPv3 - RFC 2576 Notification Filtering and Proxy Forwarding - RFC 2573
AdventNet, Inc.
418
13. What is new in SNMPv3? SNMPv3 adds support for authentication and security features to SNMPv2c. It is backward compatible with SNMPv1 and SNMPv2c. In particular, AdventNet SNMPv3 API supports all three versions of the protocol. With SNMPv1 and v2c, SNMP provides a very minimal level of security through the community string, which is sent as clear text to the agent. With SNMPv3, much stronger authentication mechanisms can be used. Due to these improved security features, device vendors can now provide a device configuration as well as monitoring. It also becomes possible to attach Java SNMPv3 agents to your applications and provide secure applications management. 14. I don't have access to an SNMPv3 agent, but I want to test the SNMPv3 features. What should I do? If you do not have an SNMPv3 agent running on your network, you can use the snmpgw (examples/low_level_api_examples/snmpapps/snmpgw.java) application available with this package to have a secure access to your SNMPv1/v2c agents. It acts as a forwarding application between SNMPv3 management application and SNMPv1/v2c agent system.
AdventNet, Inc.
419
FAQs - General
1. I am able to perform an SNMP GET successfully but I get an error if I perform an SNMP SET. Why? 2. When I make a getrequest for a particular OID using MibBrowser, I get the desired result whereas for the same OID if I make a getrequest from the command line I get a "no such variable name in the MIB" error. Why is this so? 3. How many requests, each from a different thread, can I make in the same JVM? 4. What would be the maximum packet size supported by AdventNet SNMP stack and how do I find this number? 5. How many SnmpSession instances can I open in a single SnmpAPI? 6. What are the PDU timeout units? 7. Do the sizes of a datagram vary, or are they of constant size? 8. What are the advantages of sending individual GETs compared to sending GETs with multiple OIDs? 9. I wish to build a standalone Java application by using AdventNet SNMP API. If Java is not installed, what is the approximate size of the support files that need to be installed to support the Java application? 10. If multiple requests are sent to the same destination [agent] through multiple threads concurrently, does the SNMP stack serialize them? Or does it treat them as separate requests and assign a port per request? 11. Is there a way by which I can ensure that the SNMP commands come only through AdventNet and not through a source that uses my 161 port? Can I disable SNMP to everyone but AdventNet? 12. Suppose a response comes back in 4.9 seconds on an SNMP timeout of 5 seconds. However, the CPU being very busy causes a delay of 0.2 seconds before picking up the response from the incoming buffer. In this case, would the response be used or would a timeout situation occur? 13. I get "out of environment space" error when I try to start the example application batch files in Windows. What should I do? 1. I am able to perform an SNMP GET successfully but I get an error if I perform an SNMP SET. Why? Load the corresponding MIB file to perform the SNMP SET operation. This solves the problem. Loading the MIB is a must because the type of the object is retrieved from the MIB file. To perform a SET operation, we need the OID, type, and value. If you load the corresponding MIB file, the API finds the type of the OID from the MIB. If the MIB file is not available, we need to either load the MIB file or explicitly give the type of the object. Go through the examples given in examples/low_level_api_examples/snmpapps, examples/low_level_api_examples/mibapps and in the examples/applications/ directory. Except the examples given in examples/low_level_api_examples/snmpapps directory, all other examples have the option for specifying the MIBs to be loaded. For snmpset and trap examples, loading the MIB is a must. Loading MIB files is normally done by using the -m option. The following is a sample usage of the SNMP SET command. java snmpset -m "../mibs/RFC1213-mib" 10.3.2.120 sysLocation.0 paradise sysName.0 whatever
AdventNet, Inc.
420
If you develop an application for performing SNMP SET, loading MIB files can be done by using loadMibs() of the MibOperation class in the mibs package. It is also possible to develop applications without loading MIB files. This can be done using one of the following Beans package API methods. snmpSetVariable(SnmpVar var) - specifying the OID and the corresponding value. snmpSetVariables(SnmpVar[] values) - specifying a list of OIDs and their corresponding values. This can be used while performing SET operations on multiple OIDs. snmpSet(String value, byte type) - specifying the OID value to SET and the OID type. This method is easiest to use in case of the SET operation on a single OID.
The advantage of using the MIB file is that you need not know the OID type. It is automatically read from the MIB file. 2. When I make a getrequest for a particular OID using MibBrowser I get the desired result whereas for the same OID if I make a getrequest from the command line I get a "no such variable name in the MIB" error. Why is this so ? If the OID is a scalar, MibBrowser appends a ".0 " to it and performs the getrequest. To specify an object to an SNMP agent, both the OID (which defines the type of object) and the instance (which defines the specific object of the given type) need to be provided. From the MIB, you get the OID to which an instance needs to be added. For non-tabular or scalar objects, this is an instance of "0" (e.g. sysDescr.0 or .1.3.6.1.2.1.1.1.0 ). For tabular objects, the instance is defined by the MIB, and is a sequence of one or more variables (e.g. ifInOctets.2 or tcpConnState.179.74.15.126.1192.225.226.126.197.80). In order to GET and SET SNMP variables, you need to completely specify the OID and the instance. However, you can use GETNEXT and specify the OID from the MIB (e.g. sysDescr) and get the first instance of that type from the SNMP agent. This works for all types of objects. The following usage gives you an error, java snmpget localhost .1.3.6.1.2.1.1.1 while the following usage gives the proper result. java snmpget localhost .1.3.6.1.2.1.1.1.0 3. How many requests, each from a different thread, can I make in the same JVM? You can go safely till 100-150 threads in a standard machine (64 MB, 233 MHz). 4. What would be the maximum packet size supported by AdventNet SNMP stack and how do I find this number? The maximum packet size supported is 64KB. The methods getPacketBufferSize() and setPacketBufferSize() of SnmpSession is used to get and set the packet size of the response PDU. However, this also depends on the maximum size the agent can handle. If the size exceeds the limit, the agent sends the manager a GetResponse-PDU with the value of error-status field "too big". In this case, you need to split the PDU into multiple requests and send them. Refer PDU Splitting for further details. 5. How many SnmpSession instances can I open in a single SnmpAPI? Each instance of SnmpSession takes resources. It is better to share the same session instance because apart from additional threads, each session also uses socket resources.
AdventNet, Inc.
421
6. What are the PDU timeout units? The PDU timeout values in SnmpPDU class and the SnmpSession are specified in milliseconds. All the Beans components, on the contrary, use time parameters in seconds while internally the PDU timeout parameters are set in milliseconds. The SnmpPoller bean, MibBrowser bean, etc. accept time values in seconds. 7. Do the sizes of a datagram vary, or are they of constant size? The datagram size is not a constant. It varies and the size depends on the number of the varbinds. The default underlying protocol used by AdventNet SNMP API is User Datagram Protocol (UDP). The maximum message size of a UDP packet is 64 KB. Therefore, the API could not receive packets of length greater than this value. 8. What are the advantages of sending GETs with multiple OIDs over GETs with individual OIDs? To minimize overhead and maximize throughout you should always send as many GETs in a PDU as you can (within the limits of the maximum UDP frame size of your network). The more UDP frames you send, the higher the chance for collision and the longer it takes to get the information. The real overhead is in the reception and transmission of the frame and not in the assembly and disassembly of a PDU with multiple requests. 9. I wish to build a standalone Java application by using AdventNet SNMP API. If Java is not installed, what is the approximate size of the support files that need to be installed to support the Java application? The user needs AdventNetSnmp.jar (approx. 1.5 MB) and jre1.1 (approx. 2.6 MB) from Sun MicroSystems. If you distribute our package, please read the Copyrights carefully or contact sales@adventnet.com for more details. 10. If multiple requests are sent to the same destination [agent] through multiple threads concurrently, does the SNMP stack serialize them? Or does it treat them as separate requests and assign a port per request? The SNMP stack does not serialize the requests. Ultimately, the DatagramSocket takes care of this. The DatagramSocket is opened once per session and it binds to the available port on the local machine. Concurrent requests are sent through this port. The responses can come in any order and they are matched to the request based on the request ID. Also, the DatagramSocket.receive() method is synchronized. Therefore, all the requests are sent concurrently and the responses are processed one by one inside synchronized methods in the order in which they are received. 11. Is there a way by which I can ensure that the SNMP commands come only through AdventNet and not through a source that uses my 161 port? Can I disable SNMP to everyone but AdventNet? There is no way to ensure that the SNMP commands come from a particular SNMP entity. SNMP standards do not define any method/procedure for this. The only way is to authenticate the community string, where SNMP messages from an SNMP entity can be sent with a particular community. 12. Suppose a response comes back in 4.9 seconds on an SNMP timeout of 5 seconds. However, the CPU being very busy causes a delay of 0.2 seconds before picking up the response from the incoming buffer. In this case, would the response be used or would a timeout situation occur? In this case, a timeout situation occurs.
AdventNet, Inc.
422
13. I get "out of environment space" error when I try to start the example application batch files in Windows. What should I do? This has been a problem with the Windows environment variable settings. To overcome this, you have to modify the properties of your DOS prompt. You need to right-click of the titlebar of the DOS prompt window and select Properties. Choose memory tab in the Properties dialog box and increase the value of the initial environment field (preferably 4096). It can also be solved by adding the following entry in config.sys file. SHELL=C:\Windows\COMMAND.COM/P/E:4096
AdventNet, Inc.
423
AdventNet, Inc.
424
20. I have two Psion Teklogix devices with tables containing three rows of information about another network device. I am able to read only one entry in the table. How do I read each row in the table and retrieve a couple of columns (say, the IP address and name)? This works fine when a manual request is made using SnmpTarget object. 21. Which OID should I use to set a new entry in a table? The OID of the new attribute does not exist and hence there is none that I can use. 22. Is there any limit as to the number of OIDs I can get at a time using SnmpGetList()? 23. Why is that in SnmpRequestServer the OID list is not updated for further GETNEXT operations? 24. (a) Is it true that different threads using a single instance of SnmpTarget/SnmpThread cause problems. (b) And do the APIs also create problems if each thread has its own instance of SnmpTarget. In other words, do they get/set any "global (static etc)" data that may interfere with each other? 25. I use the AdventNet stack. How do I retrieve the Not Accessible columns? 1. I use SNMPv1. While using the TrapEvent's getEnterprise API, I get the OID returned as a char string (.iso.org.dod.internet.private.enterprises....). I want to have it in its numeric form (.1.3.6.1.4...). I have not accessed the class or loaded the MIB. What should I do to get the OID in its numeric form? Even if you load the MIB using some other Bean, it is loaded in a common place and used by all the other Beans. In this case, the SnmpTrapReceiver Bean which is used in the trapreceiver application has loaded the MIB. For getting the OID in the numeric form, you can use MibOperations.getSnmpOID() which takes string argument and returns the SnmpOID and then perform an SnmpOID.toString() 2. How do I format the string values to ensure proper setting of value types Integer and Octet String while using SnmpTarget.snmpSet (String value) and SnmpTarget.snmpSet (String value, byte type) I cannot find any list of constant values to employ in this accord. You have to load the corresponding MIBs if you have not specified the type of the objects. Our API gets the type of the object from the MIB. If you do not load the corresponding MIB, you get the error Failed, MIB node unavailable for OID..x.x.x.x.x.x.x.x.x For using the methods snmpSet(String) and snmpSetList(String[]) you must load the MIB. snmpSet (String, byte): You have to specify the value and the type of the object. You can find the available types in the SnmpAPI class. You can make it simpler to use as in the example, snmpset.java in the examples/low_level_api_examples/snmpapps directory. Have a look at the addvarbind() method of this example. You can reuse or modify this method according to your requirements. snmpSetVariable(SnmpVar) and snmpSetVariables(SnmpVar[]) : These methods also perform SET by using SnmpVar objects. You can create the SnmpVar objects as created in addvarbind method or by using SnmpVar.createVariable(String value, byte type) method. Set the corresponding OIDs using the methods setObjectID(String) or setObjectIDList(String[]) 3. While using the SnmpPoller class, if I unplug the ethernet connector on my remote SNMP device, I receive timeout errors in the java console. However, there are no data exceptions in the Pollers result adaptor. How can I receive these timeout messages from the poller? In our SnmpSession.send, we do InetAddress.getByName(peername). If it throws unknownHostException, we print the error message. However, InetAddress.getByName itself does not throw the exception even after removing the network connection for the hosts whose IP address were found before removing the connection. This is the reason for the timeout messages you get.
AdventNet, Inc.
425
You need to perform poller.setSendTimeoutEvents(true). That should send timeout events when a poll fails. 4. If I call the SnmpTarget.setTimeout(5), does it mean I set the timeout to 5 seconds or 5 milliseconds? And, what do you mean by "exponentially back off"? The timeout unit specified in SnmpTarget class is seconds. But in the Low Level API, the timeout unit is in milliseconds. The exponential back off occurs after the first timeout, if the retry value is greater than zero. The exponential back off we have is the timeout period doubling after each retry. For example, for timeout=5 seconds and retries=3, Retries 0 1 2 3 Request timed out 5 seconds 15 seconds 35 seconds 75 seconds
5. How do I handle the timeout events separately while performing the SNMP operations? For handling timeouts, you can set the method to target.setSendTimeoutEvents() to true. This sends timeout events if the request fails. 6. How do I perform a GET operation in the loaded MIB by using the SnmpTarget bean? You can use the SnmpTarget.snmpGet() for scalar objects and columnar objects with instance value. For retrieving the values of a table, you can either use SnmpTarget.snmpGetBulkList() or SnmpTarget.snmpGetAllList(). 7. I use the SnmpTrapReceiver bean and the getUpTime() primitive to access the timestamp field of the SNMP traps. But it returns an incorrect value. How can I access the PDU timestamp and/or the time_received field ? The getUpTime() method returns the timestamp value of the trap PDU, which is the value of the variable sysUpTime of the agent when the event occurs. It is not the time when the trap is received. Currently, you cannot access the time_received field of SnmpPDU. You have to calculate it inside the receivedTrap method of your application. 8. The TrapReceiver bean works fine in Windows but gives the java.net.BindException error in Unix. It seems that the ports you have tried are already in use. In Unix environment, ports from 0 to 1023 are reserved. Only the root has the permission to use these ports. You can give any other port numbers other than 0 to 1023. In Solaris, you can try the following workaround. Call the trap receiver application in the /etc/rc3 file in the Solaris machine. The Solaris machine automatically listens to the port 162 when the machine is rebooted. When it receives the traps, the information is printed on the screen. The steps to be followed are: Login as root. Change directory to /etc. At the end of the /etc/rc3 file, set CLASSPATH to the AdventNetSNMP classes and the application directory. Add the command to run the trapreceiver application. Restart the machine.
AdventNet, Inc.
426
When the machine is rebooted, the trapreceiver listens to traps. Whenever a new trap is received, the trapreceiver application prints the trap information on the console. We also provide a sample utility (snmptrapforwarder.java) that serves this purpose. This forwards the traps from 162 to any port greater than1023. Compile the program and run as shown below. java snmptrapforwarder <port number greater than 1023 > The default destination port is 2001. Set CLASSPATH and run the application in one of the init script. 9. When I load the AdventnetSnmp.jar in the Visual Cafe, some of the Beans have problem in loading. What should I do? Load the swingall.jar to the component library and then load the AdventnetSnmp.jar. Now, you can see that all the components of AdventnetSnmp.jar is added to the component library of the Visual cafe. 10. I use SnmpTarget bean in an application. I can see two threads, SnmpSession() and SnmpAPI(), running after I stop using it . How do I kill these threads? The SnmpTarget Bean uses SnmpSession and SnmpAPI threads. The resources are automatically garbage collected and the SnmpServer.finalize() method does the cleanup. Unfortunately JVM takes a long time to call this method. There is no major difference in explicitly calling System.gc(). In either case, it takes around 15 minutes to release the resources. 11. How can I use the LineGraph bean? Using the LineGraph bean, you can plot the values received from a source, say a poller. The listeners of the LineGraph Bean should be notified when the values are received. The source from where the values are received should register with the ResultListener of the LineGraph Bean. For example, if the poller is the source, then poller.addResultListener(lineGraph); calls the implementation of the setResult() method and the values are plotted. 12. I use the SnmpTarget bean. What is the difference between setCommunity() and setWriteCommunity()? The setCommunity() method sets the community string of SNMPv1 and v2c messages for authentication. The setWriteCommunity() is used for SET operations only. The default community string is "public" and the default writeCommunity string is null. When writeCommunity is null, community itself is used for SET operations. Therefore, applications should explicitly set the writeCommunity before they can use it for SET operations. 13. I construct an SnmpTarget instance (say targetA) to load all the MIB files that I need inside a function. In the same block, I create another instance (say targetB) that doesn't load any MIB. Can targetB "reference" the MIBs which targetA has already loaded? i.e. Can I use targetB to GET/SET MIBs that are loaded by targetA? If I call getMibOperations() from both targetA and targetB, do these two returned "MibOperations" objects point to same "loaded" MIB files? All the SNMP Beans share the MibOperations instance and therefore it can be loaded once and used by all the other Beans. 14. If the original snmpBean object (targetA) that loaded the MIBs does not exist, can targetB still access these MIBs? Besides, where are these MIBs kept after they are loaded? All the SNMP Beans directly or indirectly extend or use SnmpServer which acts as a store house for all these types of resources. These resources are maintained in a static hash table. Therefore, the MIBs loaded from a beanA can be shared by the other beans, even if the Bean through which the MIBs is loaded is out of scope.
AdventNet, Inc.
427
15. I construct a MibOperations object first and load all of the MIB files I need using the MibOperations instance. Then I create an SnmpTarget object without loading any MIB files. Can this SnmpTarget instance GET/SET all the MIBs that are loaded by MibOperations object? You have to load the MIBs through any of the SNMP Beans (say target.loadMibs) and not directly through the MibOperations class. Only if you load through any one of the bean, can the other Beans share it. In this case, the MibOperations is not a Bean and therefore it cannot be used by the SnmpTarget Bean. 16. I use SnmpTarget to perform snmpRequest. After I perform an SnmpTarget.snmpSet() operation, I understand that SnmpTarget.getErrorCode() will return me the error code. How do I get the "Error Index" corresponding to the Error Index in a PDU? To get only the error index, add a result listener and get the response in setResult() method. Then, get the PDU from the ResultEvent object received in setResult() method by using getResponse() method. Now get the error index from the PDU using getErrindex() method defined in SnmpPDU class. Refer the following code snippet. public void setResult(ResultEvent e){ SnmpPDU pdu=(SnmpPDU)e.getResponse(); System.out.println("Error Index :"+pdu.getErrindex()); } 17. In case of ADSLConProfileTable, the format is Column.length.ascii whereas in case of accessing the attributes of any other table, the format is Column.primaryKey. Why is this so? In SnmpTable, column OIDs are defined by OID+Index. Index can be any type of Integer, String, IpAddress, NetAddress, etc. In the ADSL table, it is of type Octet String. It can be of varied length. The table can have more than one index. Since the index columns are not accessible, there is a need for separating index in order to know its value. Let us take for example, a table with two index columns, where both are not accessible. To separate this index columns of varied length, we need to know it's length. If length is not defined, we do not know which part of OID is index 1 and index 2. So it is represented by length+values. 18. When I get an Snmp OID, I can get the instance string through MibOps. Let us say I have a table indexed by a string, integer, and OID. How do I break each one of these individually from the instance using the toolkit. Yes, you can split the indices from the instance string. Follow the steps sequentially. 1. Get the instance String from MibOperations class for the SnmpOID. 2. Get the index Nodes from MibNode class. 3. Use this as arguments to call the decodeInstanceString method. Now you can get all the indices from the instance string. Following is the code snippet for doing the same. SnmpVarBind vb = target.snmpGetNextVariableBinding(); SnmpOID roid = vb.getObjectID(); String inst = mibOps.getInstanceString(roid); Vector indexNodes = node.getIndexes(mibOps); Vector v = node.getSyntax().decodeInstanceString(inst,indexNodes); StringBuffer sb = new StringBuffer(); for (int i=0;i MibNode indexNode = (MibNode) indexNodes.elementAt(i); SnmpVar var = (SnmpVar)v.elementAt(i); String s = mibOps.toString( var, mibOps.getSnmpOID(indexNode.getLabel()) ); if (var instanceof SnmpString)
AdventNet, Inc.
428
{ if (indexNode.getLabel().indexOf("Address") != -1) s = (new SnmpIpAddress(var.toBytes())).toString(); } Note: We provide the example walk_indexes.java in examples/applications directory of our package which can help you split the indexes from instance string. 19. I use AdventNet stack for SNMP v1. While adding, updating, or deleting rows, I get "no access" exception if the table contains any read-only columns. In the code, I use the addRow method in the ClippedTable class. Should these tables be handled differently? It is not possible to set the value for read-only columns. Therefore, drop the read-only columns and send the request for other columns so that you can add a row to the table which contains either the RowStatus or EntryStatus column. 20. I have two Psion Teklogix devices with tables containing three rows of information about another network device. I am able to read only one entry in the table. How do I read each row in the table and retrieve a couple of columns (say the IP address and name)? This works fine when a manual request is made using SnmpTarget object. To get the data using SnmpTable, you have to use SnmpTableListener. SnmpTableListener has the tableChanged() method which is triggered if changes are made to the table. In other words, we generate the table event in the run method of SnmpTable. Whenever it gets a row from the agent, it notifies the listener and the tableChanged event is called and the row is printed. The application has to implement this SnmpTableListener for getting the generated table events. There is no need to call the run method explicitly. The setTableOID() method starts the polling of the table automatically. Also, in the SnmpTable class, the getValueAt() method returns the value at the specified cell as a String data while the input is row and column index. In this case, you have to call the run method explicitly. This takes more time if there are many rows in the table. However, if you implement the listener, it generates an event after fetching each row. 21. Which OID should I use to set a new entry in a table? The OID of the new attribute does not exist and hence there is none that I can use. Use the OID of that column of the table and then append the instance to it. For example, ifTable.ifIndex.1 ifTable.ifIndex.2 and so on.... Here 1 and 2 are instances. To create a new row in a table, you can use the snmpset example in the examples/applications directory. The command for creating a new row to an example table is as follows. 1. java snmpset -m ../mibs/qbsystem.mib localhost -p 8001 qbSysAgentTrapDestFilter.172.16.1.52 2 qbSysAgentTrapDestComm.172.16.1.52 newrow qbSysAgentTrapDestRowStatus.172.16.1.52 4 -d Here, the new instance value is 52. This adds a new row to the table. 2. The "snmpset_without_mib" is used to set the table entries without loading the MIB. The command for creating a new row is as follows.
AdventNet, Inc.
429
java snmpset_without_mib localhost -p 8001 .1.3.6.1.2.1.25.2.1.1.11.7.1.2.172.16.1.58 INTEGER 3 .1.3.6.1.2.1.25.2.1.1.11.7.1.3.172.16.1.58 STRING hello .1.3.6.1.2.1.25.2.1.1.11.7.1.4.172.16.1.58 INTEGER 4 This command creates a new row with the following values. .1.3.6.1.2.1.25.2.1.1.11.7.1.2.172.16.1.58: 3 .1.3.6.1.2.1.25.2.1.1.11.7.1.3.172.16.1.58: hello .1.3.6.1.2.1.25.2.1.1.11.7.1.4.172.16.1.58: 4 22. Is there any limit as to the number of OIDs I can get at a time using SnmpGetList()? The SnmpGetList() method sends a single request with multiple varbinds. If the number of entries exceeds a certain limit, the size of the PDU exceeds the local constraints or the maximum message size of the manager. The maximum size of the Snmp message, which the API can encode and send, is 64kb. However, it also depends on the maximum size the agent can handle. If the number of entries exceeds the limit, the agent sends the manager a GetResponse-PDU with the value of error-status field "too big ". Therefore, the restriction is on the size of the PDU and not directly on the number of varbinds sent. 23. Why is that in SnmpRequestServer the OID list is not updated for further GETNEXT operations? In SnmpRequestServer, we do not update the OID and therefore we do not know the response received in the callback. To update the OID, perform the following in the setResult() method of ResultListener implementation. SnmpPDU pdu =(SnmpPDU)e.getResponse();//e is the ResultEvent instance SnmpOID oid=pdu.getObjectID(0); You have to form the RequestEvent with this OID for further GETNEXT operations. 24. (a) Is it true that different threads using a single instance of SnmpTarget/SnmpThread cause problems. (b) And do the APIs also create problems if each thread has its own instance of SnmpTarget. In other words, do they get/set any "global (static etc)" data that may interfere with each other? (a) Yes, it is. Some threads may try to change the OID list, which is updated for each request, when one thread is constructing the PDU for OID s in the list. (b) No, it is not a problem because it does not share any static variables. 25. I use the AdventNet stack. How do I retrieve the Not Accessible columns? We provide the following methods in the SnmpTable class of the beans package for getting the notaccessible table columns. To get the values for the nonaccessible indices: java.lang.String[][] getNotAccessibleIndex() To get the names of the nonaccessible index columns: java.lang.String[] getNotAccessibleIndexColumns() Note: Call methods setTargetHost(), loadMibs(), and setTableOID() before calling the above methods.
AdventNet, Inc.
430
AdventNet, Inc.
431
19. If I call the syncSend method after adding an SnmpClient to SnmpSession, it returns null and the callback method that I have implemented is called. Why is the callback called when I perform a synchronous SNMP request? How can I make the syncSend return the response PDU and prevent the callbacks from being called? 1. Can SnmpSession automatically detect the version of the SNMP agent on the other end? The SnmpSession is used to send/receive PDUs from any SNMP peer. Therefore, while sending requests, the session simply sends the PDU to the remote host with the PDU version set to the SnmpPDU version. If the SnmpPDU version is not specified, the SnmpSession version is used. The default version is v1. In this case, you can initially send a v1 PDU by setting the SnmpPDU version to v1. Then you can send a v2 PDU and then a v3 PDU. You can use the AdventNetSNMPv3 API for sending v1/v2/v3 requests. Depending on the response, you can find out the version of the agent. If a particular version is not supported by the agent, the request times out. 2. I use the low-level API to perform an SNMP GET. I want to get only the String and not the message. Also, I want the string in byte format instead of hex format. What should I do? The API does not have methods to return the bytes in string format. However, the SnmpVar class has the toBytes() method which returns an array of bytes. The following code snippet gets the result in string format. byte [] b = pdu.getVariableBinding(0).getVariable().toBytes(); String bstr = ""; for(int i=0; i < b.length ; i++ ) bstr+=" " +b[i]; System.out.println(bstr); 3. I use SnmpString, defined in the Snmp2 package, for both String and Octet String. While decoding a response, how do we differentiate between the two? There does not seem to be a method/field in the SnmpString attribute. The SNMP variable does not contain the Textual Convention information. DisplayString is a Textual Convention but the variable is an OCTET STRING. You need to get that from the MIB information for that MIB node, based on the OID in the variable binding. From the MibNode class, you can get the syntax for the object. When the MIB is not loaded, there is no way to distinguish. 4. I would like to use your API in a multithreaded application to collect some data. Is AdventNet SNMP API multithread safe? If you are using the low-level API, such as SnmpSession, it is multithread safe. You need to close the session to get rid of the threads. The high-level beans, such as SnmpTarget, are not designed for multiple threads to use simultaneously. They are lightweight objects that share underlying resources such as sockets, MIBs, etc. They have data corresponding to specific requests. Therefore, create one for each thread that needs one. The cleanup of the underlying threads happens when the Beans are garbage collected. Therefore, you need not worry about them, although you can try and force it by calling the gc() method after your beans go out of scope. 5. What is an OCTET in terms of bits? I am trying to determine a bandwidth utilization factor and I need to figure out how to represent an OCTET or a packet in bits. An OCTET is 8 bits. SnmpPDU.getData() returns the data to be sent or received as a byte array. The length of this array gives you the packet size in bytes.
AdventNet, Inc.
432
6. I instantiate the SnmpAPI and SnmpSession classes and various parameters, such as remoteHost, community, etc. for the session object is set. When I call Session.open(), everything works fine but the process started by the other Web-based application does not terminate. Is this because of the SNMPSession or API objects? Do I need to call close() or stop()? Both SnmpAPI and SnmpSession are threads. Stop the threads to release the resources if these objects are not used. Our API has SnmpSession.close() method to stop the session thread and SnmpAPI.close() method to stop the api thread and the session threads belonging to it. 7. How should I specify the SET value for two objects with the SYNTAX BITS and OCTET STRING object when I want to use an OCTET STRING of length 1? Set the type of the object as SnmpAPI.BITSTRING. Give the value as a string. If you want to use a string of length 1, give a single character string without quotes. Questions 8. Can I perform a multiple OID query? If yes, how many OIDs can I query with a single SNMP GET? You can perform SNMP GET operation with multiple OIDs. The SnmpPDU class is used for making multiple OID request. You can make about 200 requests within a single PDU. It also depends on the agent from which you request the data. 9. It is understood that SnmpOID only accepts dot-formatted OID strings. I would like to request SNMP values using names and dot-formatted strings. Is there a class available that can help me maintain a database of variable OIDs and names? To handle named OIDs, you need to load the corresponding MIBs. The method getSnmpOID() in MibModule and MibOperations classes accepts the name and returns the corresponding SnmpOID. Refer the javadocs of the com.adventnet.snmp.mibs package for more details. Questions 10. I always get a return for COUNTER64 in hex format. Is there a way to get a return for COUNTER64 in decimal format without performing the manual conversion? You can get the value of the Counter64 in decimal values. The toValue() method in the SnmpCounter64 class gives you the decimal values. This method returns an object which is a two dimensional array of type signed 64-bit long. 11. In view of the SnmpAdventNet getNext() facility, is there a way to detect the end of the GET rather than iterating till the end of the MIB. For example: if we do a GETNEXT on .1.3.6.1.4.1.412.1.1.1.1.1.1.47 we get .1.3.6.1.4.1.412.1.1.1.1.1.1.48 which is correct. But if we do getnext() we get .1.3.6.1.4.1.412.1.1.1.1.1.2.1 Is there a way to make this return an error instead, since we are really going to the "next item"? You can try performing a walk instead of GETNEXT. For example, if you walk on the system with OID .1.3.6.1.2.1.1, it fetches upto the number of children under it stops after that. There is a method named isInSubTree() which is used to detect the end of the walk for the corresponding parent node. 12. When I receive a PDU from the SNMP agent, how can I differentiate between a normal String and HEX-answer? By default, the API displays the value of type STRING as normal strings. However, if the string has a null character, it is interpreted as an HEX string. If you want to interpret any value as an HEX string, the method toByteString() in SnmpString class is used.
AdventNet, Inc.
433
13. I would like to set the OID of type EntryStatus but I cannot find this type in the SnmpAPI class. What should I do? What is the byte value for this type? In RFC1271-MIB, the EntryStatus is defined as follows. EntryStatus ::= INTEGER { valid(1), createRequest(2), underCreation(3), invalid(4) } So to perform a SET operation, you need to specify the type as SnmpAPI.INTEGER and the value should be in the set {1,2,3,4}. 14. How do I set UDP port explicitly for sending GET/SET/GETNEXT request? You can set the UDP port by using the method setLocalPort() in SnmpSession. The method setPort() in the SnmpTrapReceiver bean can be used to receive the traps in that port. You can also set the port using SnmpAPI. You can use any port to send traps and informrequest. 15. We would like to use a GETBULK to get several rows from our SNMP table at a time. The problem is that when I ask for 10 rows, the GETBULK returns only 6 rows and the last attribute of the sixth row is null. The sixth row seem to be truncated. Why is this so? The number of rows you get back may be limited by the PDU size permitted by your agent, manager, or transport. 16. I want to use your SNMP API to build a PDU packet. Is there a way to encode the PDU packet without sending it? I do not use UDP/IP to send packets. I use my own transport mechanism. As of now, the encoding of the PDU packet is done only when I actually send it out. Do you have a separate encoding function? As of now, there is no separate public method to encode the PDU. Therefore, you need to use your own encoding routines. We may in future provide an encoding routine to suite your design. 17. The problem is that the callback method is not invoked and deadlock occurs in the application while performing the SET operation. The table row is created in host 192.168.43.221 and the OID and values are as follows. .1.3.6.1.4.1.6251.1.1.1.1.1.1.1.3.1.1:OCTET_STRING : 1234 .1.3.6.1.4.1.6251.1.1.1.1.1.1.1.7.1.1:INTEGER : 4 (createAndGo) .1.3.6.1.4.1.6251.1.1.1.1.1.1.1.8.1.1:OCTET_STRING:SSSSSSSSSSSSSSSSSS. In SnmpPDU, you set the community as private. In SnmpSession, it is public by default. If the authenticate (pdu, writecommunity) method returns false, SnmpSession does not call the callback. Therefore, the following method is used. SnmpSession.setWriteCommunity(java.lang.String writeCommunity) Set writeCommunity for outgoing requests 18. If I have more than one SnmpClient in SnmpSession, the callback method of all the SnmpClients is called whenever the session receives a response. How can I tell the SnmpSession that only one of the clients should receive the response for a particular request? The method "addSnmpClientWithID(SnmpClient)" provided in the SnmpSession in the AdventNet SNMP API release 3.3, helps you to do this. Instead of "addSnmpClient(SnmpClient)", use "addSnmpClientWithID(SnmpClient)" to add the SnmpClient. This method returns an integer called ClientID, which is associated with this client. Therefore, whenever an asynchronous SNMP request is sent using the "send(SnmpPDU)" method, set this clientID in the PDU using the method "setClientID(int)" in SnmpPDU. By doing this, only the callback method of the SnmpClient, which corresponds to that ID is called.
AdventNet, Inc.
434
The following code snippet illustrates this feature. SnmpSession session = new SnmpSession(api); /* where api is the SnmpAPI instance. */ session.open(); int clientID = session.addSnmpClientWithID(snmpClient); /* where snmpClient is the instance of SnmpClient. */ SnmpPDU pdu = new SnmpPDU(); /* set all relevent parameters */ pdu.setClientID(clientID); session.send(pdu); /* asynchronous SNMP request */ 19. If I call the syncSend method after adding an SnmpClient to SnmpSession, it returns null and the callback method that I have implemented is called. Why is the callback called when I perform a synchronous SNMP request? How can I make the syncSend return the response PDU and prevent the callbacks from being called? After an SnmpClient is added to SnmpSession, all the responses received are notified to the client(s) added and the session becomes specific only to the asynchronous requests. This problem has been fixed in the release 3.3 of AdventNet SNMP API. Now even after adding an SnmpClient, a call to "syncSend" fetches you the response PDU. Note: 1. You should set the clientID in SnmpPDU (using the method "setClientID(int)") to zero before sending the request. This makes the syncSend method return the response PDU and no callbacks are called. You need not set it, unless you reuse any other SnmpPDU instance because the default value of clientID in SnmpPDU is zero. 2. Here all the clients are added to the SnmpSession, should be added only using the method "addSnmpClientWithID(SnmpClient)". If any of the clients is added using the method "addSnmpClient(SnmpClient)", then the callback method of these clients are called and the syncSend does not return the response PDU.
AdventNet, Inc.
435
In this case, assume that you wish to obtain the instance corresponding to the particular tcpConnRemAddress. The index for tcpConnTable and the indexNodes vector contain nodes corresponding to tcpConnLocalAddress, tcpConnLocalPort, tcpConnRemAddress, and tcpConnRemPort in the same order. The indexVector contains the following SnmpVar objects in the specified order. SnmpIpAddress corresponding to 128.253.154.64. SnmpInt corresponding to port 23. SnmpIpAddress corresponding to 128.253.154.3 SnmpInt corresponding to port 1111.
The return value, in this case, contains the int array containing 128.253.154.64.23.128.253.154.3.1111, the subIDs forming components of the array.
AdventNet, Inc.
436
The decodeInstanceString() returns a vector of SnmpVar of the index nodes, given the instance string and index nodes. You can see the walk_indexes example in applications directory to use decodeInstanceString(). For augments, you need to give the index nodes vector. IMPLIED is supported. Therefore, if the last of the index node vector elements has an attached IMPLIED clause in the MIB, it is taken note of during the encoding. The AUGMENTS support is not very neat as of now. As it is at present, for an augmented node such as alphaEntry AUGMENTS betaEntry, the indexNames for alphaEntry will be the same as the indexNames for betaEntry. 2. How do I know if a table is augmented (from the interface)? How do I get a reference to the conceptual index? For Augments you still have to give the index nodes vector. So there is not much of a difference. IMPLIED is supported. So if the last of the index node vector elements has an attached IMPLIED clause in the MIB, it will be taken note of during the encoding. The AUGMENTS support is not very neat as of now. As it is at present, for an augmented node such as alphaEntry AUGMENTS betaEntry , the indexNames for alphaEntry will be the same as the indexNames for betaEntry. 3. I use the method loadMibModules(String file) of MibOperations class to load and unload MIB modules. Is there a class that supports unloading selected or all loaded modules? In MibOperations, you have methods unloadMibModule(String name) and unloadMibModule(MibModule module) to unload a MIB. You can also use MibBrowser to unload MIBs. 4. In my manager application, do I need to call SnmpTarget.loadMib() to load vendor-specific private MIB files? Can I GET/SET any value without loading MIB files? If you specify the OID in the numbered format, you need not load the MIB for SNMP GET. But for SNMP SET operation, the corresponding MIB file should be loaded because it takes the type of the object from the MIB file. In the snmpset example provided in the examples/low_level_api_examples\snmpapps, we specify the type of the object also as an argument. In this case, you need not load the MIB file. Therefore, if you specify the numbered OID, you need not perform SnmpTarget.loadMib() for GET, whereas for performing SET operation, loading the MIB file is a must. Further, for using the methods snmpSet(String) and snmpSetList(String[]), you must load the MIB. For using snmpSet(String, byte), you need to specify the value and the type of the object. The snmpSetVariable(SnmpVar) and snmpSetVariables(SnmpVar[]) methods perform SET by using SnmpVar objects. In this case, you need not load the MIB file. If you load MIB from one Bean, it is loaded in a common place and used by all other beans. 5. I use the loadMibs() method on SnmpTarget to load the MIB definitions. This works fine but takes longer time. Is it possible to precompile the MIB files and load a binary file at run time? We provide methods to serialize the MibModule and load from the serialized module. For very small MIB files, serialization does not help much and for larger files, the load time is decreased by 30%. 6. How do I load the MIBs in my application? You can load MIBs in your application by using the methods loadMibModule() and loadMibModules() of the MibOperations class. You can look into the examples/low_level_api_examples/mibapps directory for more information. The following code snippet gives the usage of the loadMibModule() method for loading MIBs. MibOperations mibOps = new MibOperations(); mibOps.loadMibModules("c:\mibs\RFC1213-MIB"); //specify the name of the MIB directly
AdventNet, Inc.
437
AdventNet SNMP API supports the following options for loading MIBs. Loading MIBs directly Loading MIBs as compiled files Loading MIBs from a database Loading MIBs as serialized files
Please go through the Using MIBs in Applications section for more details. 7. How do I get the root OID and the labels of the variables? If you want to get the root of a module, you need to use the getRootNode() of the MibModule class. You can get the label of a node by using the getLabel() method of the MibNode class, provided you have loaded the corresponding MIBs. 8. Can SNMP API return me the string value that is defined in the MIB, when I receive the response? If you want to view the enumerated label for the output value, you have to load the MIB in the receiver side. MibOperations mibOps = new MibOperations(); mibOps.loadMibModules("mib file"); For example, if you have SnmpVarBind and if the output value is major(3), you can get the required String as follows. mibOps.toString(snmpvarbind)); This will return MySeverity:-->major(3). If you want only the enumeration label, then use the following code. SnmpInt in = (SnmpInt)snmpvarbind.getVariable(); MibNode mn = mibOps.getMibNode(snmpvarbind.getObjectID().toString()); LeafSyntax ls = mn.getSyntax(); ls.getLabel(in.intValue()) will give you the enumeration label "major".
AdventNet, Inc.
438
1. I created a test program using SnmpTarget. When I run it in Internet Explorer 4, I get the following message.com.ms.security.security.ExceptionEx[com/adventnet/snmp/snmp2/SnmpSessi on.open}: cannot access 6001. What do I do?
By default, IE4 does not allow Java applets to open sockets. You need to explicitly modify the browser settings or enable Java applets to use network ports. SAS, provided with AdventNet SNMP, can be used to get rid of the security-related problems. The distribution includes an integrated web server and SAS, which is used to load the applet. This involves running the server, and loading the applet of the server. Refer the SAS documentation for details on running and using the SAS. 2. Does AdventNet's SAS work with Apache as the web server or does it run only with the AdventNet Web Server? Does the AdventNet Web Server run with Linux PC? The AdventNet SAS server can run with any web server. The web server that is bundled along with the product is platform independent. 3. I want to load applet that I created through the applet viewer. What should I do? The HTML file should contain the name of the applet's class file within the applet tags. You need to set CLASSPATH to the AdventNet classes and the necessary JDK classes, such as swingall.jar, and give one of the following commands. appletviewer// will work for the JDK's between 1.1.6 and 1.2 appletviewer -J-Xbootclasspath:// For JDK 1.2 appletviewer http:// //will work in all JDK versions
4. I want to view the applet that I created in a web browser. What should I do? You need to create a jar file that contains the example you have created and copy the jar file to the AdventNet classes directory. Ensure that the web server and the SAS is started and load the html file. http://localhost:8282/
AdventNet, Inc.
439
If the applets contain any JFC/Swing components, you need to include a few additional lines in the HTML file so that the web browsers invoke the proper plug-in. Then load the applet and check if it runs both in IE and Netscape. The complete HTML file to load an example applet is given in the following link. HTML source for loading the SnmpGetApplet example. This HTML file loads the applet by setting the code and codebase values. The following line needs to be included to load the applet by using the jar. PARAM NAME = ARCHIVE VALUE = jar file name 5. How do I make my applet connect to SAS when it is loaded through the web server? If you use low-level API, use the SnmpSession.open(api) instead of SnmpSession.open() when you open the Snmp Session in your applet. This automatically connects to SAS if it is alive. If you use Beans components, use the applet constructor instead of the default constructor. 6. The SAS server runs in my web server host. Why does not my applet connect to SAS? SAS creates a file called SASPort.html when it is stared. The applet looks for that file to get the port number to connect to SAS. The file has to be created in the same directory in which your applet HTML file is present. Use the -d option to specify the directory for the SASPort file and make sure your applet HTML file is in this directory. 7. Why do I get an Applet Security exception when I load a MIB file in the example applet that I developed? This is because your applet classes are not in the CLASSPATH. If your applet is loaded from code base, which is not in you CLASSPATH, in your HTML file, you can neither read/write files nor connect to any remote hosts. 8. Why do I get a Security exception while locally loading a MIB file in the MibBrowser applet using Netscape? Netscape4.x does not allow classes loaded from the local system to access the disk unless they are signed. One option is to add the following line to prefs.js in Netscape users directory if you wish to use from local system. user_pref(signed.applets.low_security_for_local_classes", true); The other option is to put the classes in a jar file and sign them. 9. After starting the Web Server/SAS, if I try to connect through the browser by giving the URL http://localhost:8282, I get the "remote machine timed out" error. However, I can see the web server running at port 8282. This error can occur if the web browser settings having the proxy connections enabled. This is because some proxy servers cannot resolve to the localhost. You can give the host name of the machine instead of localhost or you can disable the proxy settings in the browser.
AdventNet, Inc.
440
The SnmpEJBServer is part of this EJB architecture, which allows the network management without any restrictions. This SnmpEJBServer is invoked and bound to the RMI registry and the application server does a lookup and gets the handle to the SnmpEJBServer. Now, any incoming client request is passed to this handle, which in turn calls the rmi classes, and the SNMP operations are performed. 2. There are problems in deploying your three EJB jar files in Inprise application server. I get an error saying the jar files are not EJB spec. compliant. The EJB Jar files supplied with the AdventNetSNMP API package are standard Jar files and are compliant to EJB 1.1 spec. Therefore to deploy in different application servers, you need to supply the corresponding xml files used by the application server. For example, for Inprise application server 4.5, you need to archive ejb-inprise.xml file in the 'META-INF' directory to the standard Jar files from AdventNetSNMP API. 3. I deploy the SNMpTargetEJB.jar file with the help of weblogic 5.1 deployer but while loading it, I get "Class not found" exception. Why is that so? The AdventNetSNMP package should be added to the WebLogic 5.1 CLASSPATH as shown below. 1. Open the startWebLogic.bat file in <weblogic_HOME> directory in a text editor. 2. Add the following line to the PRE_CLASSPATH variable. set PRE_CLASSPATH=<AdventNet_HOME>\AdventNetSnmpV3\classes; Here, '<AdventNet_HOME>' is the directory in which the AdventNetSNMP API was installed. 3. Edit setEnv.bat file in <WebLogic-HOME> directory and set the AdventNetSNMP API classes directory in the CLASSPATH variable. Make sure the AdventNet package comes first in the CLASSPATH setting.
AdventNet, Inc.
441
2. Our product currently uses the com.adventnet.snmp.rmi package, the SnmpTarget interface, and the snmpGet method for data retrieval. Can I combine multiple varbinds into a single SNMP GET message? Can I use snmpGetList or snmpGetAllList? How are they different? How do I control the size without exceeding the 484 byte SNMP payload limit when I add varbinds? The snmpGetList method makes a get request for a list of OIDs while the snmpGetAllList walks from a particular OID. You can use the snmpGetList to combine multiple varbinds and perform a GET operation. While constructing a PDU, you have to check its size. If it exceeds the limit, it has to be reconstructed by splitting the PDU. You can get the length of the PDU by using the method pdu.getEncodedLength(). However, you have to set the community on the PDU to get the right encoded length. If the length exceeds the limit, split the number of varbinds to be sent into two sets and construct two PDUs.
AdventNet, Inc.
442
3. RMI requests are slow in Windows NT and Windows 2000 machines. Why is this so? This is because, in Windows NT and Windows 2000, while making SNMP requests through RMI, the RMI Registry does a DNS lookup for the IP address specified. The following workaround should solve the problem. Open the 'hosts' file present at <WINNT_HOME>\system32\drivers\etc directory, where '<WINNT_HOME>' is the directory in which Win NT was installed. Add the IP Address and the hostname of the machine where the agent runs. It has to be separated by a space as a new entry at the end of the file. For example, 192.168.7.232 AgentMachine Save this file.
4. I always get "Request Timed Out to 10.0.14.79" and 10.0.14.79 is our simulator. However, it works fine while using snmpget in applications directory. This error might occur due to the following reasons. The agent might be down: This reason is ruled out because nondistributed examples work for the same agent. The agent is slow in responding to the request: Increase the timeout value. By default, it is 5 seconds. The port at which the agent listens might be different: Set the port by using the '-p' option. SocketPermission for accepting connections may not be set: In the java.policy file in <JavaHome>\jre\lib\security directory, modify the code as follows.
java.net.SocketPermission "*:161-60000", "listen,connect,accept"; If you do not have the entry "accept", then you might face the timeout problem. Assuming that you have permissions to listen and connect to the socket, create the SnmpTarget and send the requests. The timeout occurs if you do not have permission to accept messages through the socket. Verify the entry in your policy file.
AdventNet, Inc.
443
For example, the loadMibs(String fileName) in SnmpTarget of corba package catches exception when there is an error while loading of mibs. For few methods, such as snmpSet, and snmpSendTrap in SnmpTarget (for which the exceptions are thrown), you can get the snmp error messages. With the current API, it is not possible to get error messages, such as the Invalid OID Format on the client side. 2. How do I use Visigenic Visibroker ORB with AdventNet CORBA API? The AdventNet SNMP CORBA API can be used with Visibroker. Following are the steps that should be followed. 1. Start osagent. 2. Start nameserv <name> where name is an identifier. 3. After setting the PATH and CLASSPATH, start the CORBA server using the following command. vbj-DSVCnameroot=<name> com.adventnet.snmp.corba.server where name is the identifier used to start the nameserv. 4. You can start the client application by using the following command. vbj -DSVCnameroot=<name> corbaget host oid where name is the identifier used to start the nameserv. 3. Which IDL compiler is used to make those ORBs? We use Sun's idltojava 1.2 to generate our java files. 4. What version of CORBA is supported/implemented by the AdventNetSNMP API? Our SNMP API conforms to the CORBA 2.0 specification. Interoperability, the key goal, was added in CORBA 2.0 specification based on Internet Inter ORB Protocol (IIOP). Also IIOP works across Internet and TCP/IP implementations. Various application server providers use IIOP and therefore they can be integrated with CORBA. The support of IIOP is JVM dependent. JDK 1.1 and higher are known to support IIOP.
AdventNet, Inc.
444
Javadocs
High-Level API Low-Level API MIBs API SAS API Distributed API Utils Classes
Javadocs contains the classes and methods pertaining to various modules of SNMP API, which are categorized as follows.
High-Level API
Description This package consists of AdventNet SNMP Java Bean com.adventnet.snmp.beans components that can be imported into any Java Bean Builders. This package consists of the AdventNet SNMP UI Beans, such com.adventnet.snmp.ui as the MibBrowser bean, TableBean, etc. Package
Low-Level API
Description This package defines some basic interfaces for a com.adventnet.management.transport generic transport provider framework communication between a client and server. This package implements snmp communication and snmp variables defined in ASN.1, such as SnmpOID, com.adventnet.snmp.snmp2 SnmpInteger, etc. Package
MIBs API
Description This package provides all the MIB handling support, such as MIB com.adventnet.snmp.mibs loading, unloading, etc. Package
SAS API
Description This package provides classes that facilitates communication between network management applets and managed devices com.adventnet.snmp.sas where direct communication is prohibited due to applet security policies. Package
AdventNet, Inc.
445
Distributed API
Description This package provides the CORBA access to AdventNet SNMP com.adventnet.snmp.corba API. This package enables building and deploying scalable applications that leverage the scalability of the Multi-tier Application Server architectures, that support a very large com.adventnet.snmp.ejb number of users, load-balancing, fail-over, transactions and other high-end capabilities. This package consists of Java interfaces that facilitates network com.adventnet.snmp.rmi management using RMI from remote clients to perform SNMP operations. Package
Utils Classes
Description This package consists of AdventNet Utils classes. It is mainly used for com.adventnet.utils Internationalization and for logging debug messages. Refer the Javadocs for the AdventNet SNMP API for more information. Package
AdventNet, Inc.
446