Sunteți pe pagina 1din 447

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

API Overview .......................................................................................................... 16


High-Level API Architecture............................................................................................... 17 Low-Level API Architecture ............................................................................................... 19 MIBs API Architecture........................................................................................................ 21 SAS API Architecture......................................................................................................... 22 RMI API Architecture ......................................................................................................... 24 CORBA API Architecture ................................................................................................... 26 EJB API Architecture ......................................................................................................... 27

Development Environment for API ....................................................................... 29


Setting Up for High-Level API............................................................................................ 30 Setting Up for Low-Level API............................................................................................. 31 Setting Up for RMI API ...................................................................................................... 32 Setting Up for CORBA API ................................................................................................ 34 Setting Up for EJB API ...................................................................................................... 36

Using MIBs in Applications ................................................................................... 37


Loading MIBs..................................................................................................................... 38
Loading MIBs Directly .................................................................................................................... 39 Loading from Serialized Files ........................................................................................................ 42 Loading Compiled MIBs................................................................................................................. 44 Loading from Database.................................................................................................................. 46

Unloading MIBs ................................................................................................................. 48 Parsing MIBs ..................................................................................................................... 49


Parsing Levels ............................................................................................................................... 50 Checks for Various Parsing Levels................................................................................................ 52 Checks in Detail ............................................................................................................................. 54

Accessing Node Information.............................................................................................. 64 Retrieving MIB Information ................................................................................................ 66 Exceptions and Error Messages........................................................................................ 67 Database Schema ............................................................................................................. 73 Macro Type Constructs...................................................................................................... 77

AdventNet, Inc.

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

Configuring SNMP Agent Parameters .................................................................. 83


SNMP Version ................................................................................................................... 84 SNMP Version ................................................................................................................... 85 Host Name......................................................................................................................... 86 Port Number ...................................................................................................................... 87 Community Name .............................................................................................................. 88 Timeout and Retries .......................................................................................................... 89 Max Repetitions ................................................................................................................. 90 Non Repeaters................................................................................................................... 91 Trap Parameters................................................................................................................ 92

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

Textual Conventions ........................................................................................................ 145


Overview ...................................................................................................................................... 146 DateAndTime ............................................................................................................................... 148 MacAddress ................................................................................................................................. 151

Data Retrieval Operations ................................................................................... 153


SNMP GET ...................................................................................................................... 154 SNMP GETNEXT ............................................................................................................ 158 SNMP GETBULK............................................................................................................. 160 Polling Data ..................................................................................................................... 162

Data Altering Operations ..................................................................................... 164


SNMP SET ...................................................................................................................... 165 Setting Values for Datatypes ........................................................................................... 168

AdventNet, Inc.

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

Traps and Notifications ....................................................................................... 169


Receiving Notifications .................................................................................................... 170 Sending Notifications ....................................................................................................... 174

Table Handling in Applications ........................................................................... 176


SNMP Table Basics......................................................................................................... 177 Fetching Tables ............................................................................................................... 179 Getting Row Data ............................................................................................................ 184 Getting Column Data ....................................................................................................... 186 Polling Table Data ........................................................................................................... 188 Table with Notaccessible Index ....................................................................................... 190 Modifying Table Data....................................................................................................... 191 Adding a Row .................................................................................................................. 193 Deleting a Row ................................................................................................................ 196 Other Table Operations ................................................................................................... 198

Exceptions and Error Handling........................................................................... 199


Error Handling.................................................................................................................. 200 High-Level API Exceptions .............................................................................................. 202 High-Level API Error Messages ...................................................................................... 203 Low-Level API Error Messages ....................................................................................... 205

Developing SNMP Application as Java Applet .................................................. 209


Support Through SAS...................................................................................................... 210 Extending SAS................................................................................................................. 218 Support Through HTTP ................................................................................................... 222 Applications of SAS API .................................................................................................. 226 Installation Notes ............................................................................................................. 228

Using Transport Providers .................................................................................. 229


SNMP Transport Provider................................................................................................ 230 SAS Transport Provider................................................................................................... 231 Custom Transport Provider.............................................................................................. 232 Internet Protocol Version 6 .............................................................................................. 234

Internationalization .............................................................................................. 237


Using High-Level API....................................................................................................... 238 Using Low-Level API ....................................................................................................... 239

Logging Management Applications.................................................................... 240


Logging Mechanism......................................................................................................... 241

Deployment Instructions ..................................................................................... 244


Deploying Applications .................................................................................................... 245 Deploying Applets............................................................................................................ 246 Deploying EJB Applications............................................................................................. 247

AdventNet, Inc.

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

Examples .............................................................................................................. 253


Setting Up the Environment............................................................................................. 254
Using Applications ....................................................................................................................... 255 Running Applets........................................................................................................................... 258

Data Retrieval Examples ................................................................................................. 259


SNMP GET .................................................................................................................................. 260 SNMP GETNEXT......................................................................................................................... 262 SNMP GETBULK......................................................................................................................... 263 SNMP Walk.................................................................................................................................. 264

Data Altering Examples ................................................................................................... 265


SNMP SET................................................................................................................................... 266 SNMP SET Without Using MIB.................................................................................................... 268

Notification and Inform Examples .................................................................................... 269


Trap Receiver .............................................................................................................................. 270 Send Notifications ........................................................................................................................ 272 Send Inform Request ................................................................................................................... 274 Send v2c Inform........................................................................................................................... 275 Receive v2c Inform ...................................................................................................................... 276

Table Handling Examples................................................................................................ 277


Table Retrieval - Non UI .............................................................................................................. 278 Retrieve Table - UI....................................................................................................................... 281 Walk Indexes ............................................................................................................................... 286 Get By Index ................................................................................................................................ 287 Set Table Value ........................................................................................................................... 288 Encode Table Index ..................................................................................................................... 289 Get Column.................................................................................................................................. 290 Get Row ....................................................................................................................................... 291 Get Table Info .............................................................................................................................. 292 SNMP CORBA............................................................................................................................. 292

MIB Handling Examples .................................................................................................. 294


MIB Node Details ......................................................................................................................... 295 Leaf Node Details ........................................................................................................................ 296 JFC MIB Tree............................................................................................................................... 297

Other Examples ............................................................................................................... 298


Request Server Demo ................................................................................................................. 299 RMI Request Server Demo.......................................................................................................... 300 SnmpPoller Demo I...................................................................................................................... 302 RMI Applet Demo......................................................................................................................... 304 Property Settings Demo............................................................................................................... 306 Line Graph Demo......................................................................................................................... 308

AdventNet, Inc.

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

Tutorials ................................................................................................................ 309


Overview.......................................................................................................................... 310
Beans API Tutorial ....................................................................................................................... 311 Low-Level API Tutorial................................................................................................................. 312 MIBs API Tutorial ......................................................................................................................... 314 SAS API Tutorial .......................................................................................................................... 315

Data Retrieval Tutorials ................................................................................................... 316


GET, GETNEXT Using High-Level API ....................................................................................... 317 SNMP GET, GETNEXT (UI) Using High-Level API..................................................................... 319 SNMP GET, GETNEXT Using Low-Level API ............................................................................ 323 SNMP GET, GETNEXT for Applets............................................................................................. 326 SNMP GET Using SAS Transport Framework ............................................................................ 328 SNMP GET Using TCP................................................................................................................ 329 Polling with SnmpPoller ............................................................................................................... 332

Data Altering Tutorials ..................................................................................................... 334


SNMP SET Using High-Level API ............................................................................................... 335 SNMP SET (UI) Using High-Level API ........................................................................................ 337 SNMP SET Using Low-Level API ................................................................................................ 340

Trap Tutorials................................................................................................................... 343


Receive Trap Using High-Level API ............................................................................................ 344 Send Trap Using High-Level API.................................................................................................346 Receive Trap (UI) Using High-Level API ..................................................................................... 347 Send and Receive Trap (UI) Using High-Level API..................................................................... 349 Receive Trap (UI) Using TrapBrowser......................................................................................... 352 Receive Trap Using Low-Level API ............................................................................................. 355 Send Trap Using Low-Level API..................................................................................................358 Receive Traps for Applets............................................................................................................ 361

Table Handling Tutorials.................................................................................................. 364


Retrieve Table with TableBean.................................................................................................... 365 Retrieve Table with SnmpTable................................................................................................... 367 Retrieve Table with SnmpAugmentTable .................................................................................... 369 Retrieve Table with SnmpTableModel......................................................................................... 371 Retrieve Table with SnmpTablePanel ......................................................................................... 373 Retrieve Table with SnmpTarget .................................................................................................375

MIB Handling Tutorials .................................................................................................... 377


Traverse MIB (UI) with MibTree................................................................................................... 378 Browse MIB (UI) with MibBrowser ............................................................................................... 381 Retrieve MIB Node Information with MIBs API ............................................................................ 382

Other Tutorials ................................................................................................................. 384


Graphs with LineGraphBean ....................................................................................................... 385 Address and Name Lookup ......................................................................................................... 387

AdventNet, Inc.

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

SAS as an Application ................................................................................................................. 389 SAS as Part of an Application...................................................................................................... 391

Complete Example .......................................................................................................... 393

Performance Metrics............................................................................................ 394


Performance Numbers for Modules................................................................................. 395 Performance Numbers for MIB Loading Options............................................................. 396 Performance Numbers for Traps ..................................................................................... 397

Migration Guide .................................................................................................... 398


Migration from 3.x to 4.0 .................................................................................................. 399
High-Level API Changes.............................................................................................................. 400 Low-Level API.............................................................................................................................. 401 MIBs API Changes....................................................................................................................... 406

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 SNMPAPI 4 SNMPv2c :: Help Documentation

Developing SNMPv2c Management Applications


Choosing the Application Architecture discusses the various kinds of network management applications and applets that can be developed using AdventNet SNMP API. API Overview discusses the usage of AdventNet SNMP API for developing the management applications and applets. It also explains how to work with the various Java packages available with this product. Using MIBs in Applications discusses the MIB-related aspects while developing the management applications. Configuring SNMP Agent Parameters discusses the common SNMPv2c parameters that need to be set while developing the applications and applets. Handling Datatypes explains about the basic datatypes, application datatypes, and textual conventions. Data Retrieval Operations discusses the data retrieval operations such as GET, GETNEXT, GETBULK, and polling. Data Altering Operations discusses the SNMP SET operation using AdventNet SNMP API. Traps and Notifications explains how to receive and send traps using AdventNet SNMP API. Table Handling in Applications explains the various table-related operations that can be performed using AdventNet SNMP API. Exceptions and Error Handling details the various errors and exceptions that are generated while using AdventNet SNMP API. Developing SNMP Application as Java Applet explains the usage of SAS in developing management applets. It also discusses the communication between applets on Java browsers that do not permit socket access to any host other than the applet host. Using Transport Providers discusses the transport providers that enable you to implement the protocol of your choice for SNMP communication. Internationalization explains the internationalization support available in AdventNet SNMP API. Logging Management Applications explains the feature used by applications to log messages while communicating with the agent. Deployment Instructions explains the steps involved in deploying the applications and applets. Examples gives the detailed instructions on the usage of various command line tools and applications that are bundled with the AdventNet SNMP API product to query the SNMP devices/applications. Tutorials helps you get familiar with the development using AdventNet SNMP API. Sample Java programs are available that can be compiled and run. Performance Metrics gives the performance numbers for the various modules of AdventNet SNMP API. Migration Guide describes the changes that have been made in this release and guides the user to upgrade to AdventNet SNMP API 4. This section is useful for the existing AdventNet SNMP API users who are migrating to the latest release. New users can skip this section.

AdventNet, Inc.

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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 SNMPAPI 4 SNMPv2c :: Help Documentation

Choosing the Application Architecture


Overview Management Console Applications Middle-Tier Management Servers Web Craft Interfaces

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.

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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 application that is developed can be any of the following.

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.

Network Management and Device Management


Network management is primarily concerned with managing an entire network that is made up of number of devices. Device management is considered with managing a device as an individual entity. A management application developed for network management monitors the network and the devices in the network. A device management application is used to manage a particular device in the network. Here, the network itself is used only as a medium to monitor the device remotely. The application does not have any control over the network.

Generic and Customized Management Applications


The network management needs mandate the management application to be as generic as possible or custom-tailored for a specific network or device. A generic management application typically loads any MIB, receive any trap message, communicate with any type of device, query and poll any SNMP node, and so on. Although a generic management application has its advantages, its utility is limited. Even the simplest management operations might need to be done repetitively. Customized applications have specific user interface and most of the complex requests can be handled in few mouse clicks. Graphical representation and automating several routine tasks are the part of the customized approach. The applications can also completely isolate the user from the underlying protocol used. One disadvantage is that they are tailor made for the associated MIB. Any change in the MIB is difficult to handle in the application.

AdventNet, Inc.

10

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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.

Using AdventNet SNMP API


AdventNet SNMP API with its hierarchy of Java packages enables developing the above-mentioned type of applications in a simpler and quicker way. The various packages available with this product allows flexible selection of the desired level of library support. You can either access detailed SNMP information using low-level API or choose higher-level Java Beans for simpler programming.

AdventNet, Inc.

11

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

Management Console Applications


When you are looking to build a management application where: there is no constraint on the size of the application the management console application need not be dynamic the performance of the management console is critical all the management operations need not be distributed or centralized

you can go in for building standalone management console application.

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

Middle-Tier Management Servers


The multi-tier architecture includes a back-end database, a middle tier of servers and clients. The back-end database has all the common data. The middle tier usually consists of a set of servers that performs processing. The client tier consists of thin clients, which can be HTML-only, Java applets, Java applications, or other suitable clients. When you are looking to build a management application, where: the management application has to be thin multiple administrators using the management application should be able to talk to the server all the processing of data should be done at the server side and passed on to the client there is a need for more then one management application using a centralized server

you can opt for this middle-tier architecture.

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

Web Craft Interfaces


When you are looking to build a management application, where: the management application has to be viewed from anywhere by using a web browser there is a need for more than one administrator to manage there is a size restriction for the management application you are looking for a web-based tool for managing your network

you can opt for building applets.

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

High-Level API Architecture


The high level API is a set of UI and non-UI Java components, which act as a standard reference base for both application developer and tool vendors. This allows building more flexible applications, applets, and components. A number of enhancements have been added as well, making the use of the high-level APIs much more productive in building applications. The components can be used in any Java Bean Builder or directly in the Java code. The purpose of the high-level APIs is to make it easier to develop management applications using the SNMP libraries. The benefits of using the high-level APIs include: Increased functionality using library methods, which includes the performance of GET, GETNEXT, GETBULK, and SET operations on multiple variables, sending traps, getting all instances of variables under an object identifier, etc. Usage of AdventNet SNMP Java components in Bean Builder. Increased support for SNMP tables. The high-level beans are lightweight sharing the underlying resources, such as SnmpSession, SnmpAPI, and MibOperations. The bean components hide the complexities of using the lowlevel APIs. While instantiating these beans in applets, you have to pass the applet instance so that it can internally use the SAS for performing SNMP operations. Therefore, all the complexities of using low-level APIs and SAS are hidden from the user and taken care by the high-level API. Sometimes, it may become necessary for a bean to use a separate session instead of sharing the same session with other beans. In such cases, the beans have to be instantiated with the port and session name as arguments. To use the transport provider, where you can plug-in your own transport protocol, the constructor that takes ProtocolOptions as the argument can be used. The API implements the UDP/IP as the default protocol implementation and provides TCP/IP as the reference implementation. For synchronous operations, the SnmpTarget bean can be used and for asynchronous operations, the SnmpRequestServer bean can be used. The MibBrowser bean which is a full fledged UI component for management operations, makes use of the SnmpRequestServer bean.

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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.

SnmpTable - for working with tabular SNMP data.

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

Low-Level API Architecture


The low-level API is the collection of basic classes that implement SNMP according to v1, v2c, and v3 standards. The low-level API consists of the snmp2 Java package, which enables you to work directly with the details of SNMP and helps reduce the size of your management applet or application. The following figure illustrates the organization of the low-level SNMP API packages.

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

MIBs API Architecture


Applications or applets can access MIB information through the MIBs API. The MIB information can be present in a text file, database, or a serialized file. The MIBs API provides methods to access MIB node information, such as syntax (the data type of the node), access type (read, write, etc.), status (obsolete, current, etc.) and others. Based on these information, the application or applet can perform the various SNMP operations.

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

SAS API Architecture


Management clients that run as applets can be developed using the AdventNet SNMP API. Due to the Java security restrictions, applets cannot directly communicate with SNMP agents. To overcome this, the SAS server can be used as a gateway between the applet (SAS client) and the agent. It should be noted that the SAS server has to run on the same machine from which the applet is downloaded. The applet can connect with the SAS server and send the SNMP requests to SAS, which in turn forwards it to the corresponding SNMP agent. When SAS receives the response, it sends it back to the applet or the SAS client.

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

RMI API Architecture


The RMI APIs support using RMI from remote clients to perform SNMP operations. The advantage of using the RMI APIs is to allow a server to perform the SNMP functions, while the clients only make the RMI calls to the server. In other words, the server can run on the web server, while applets make RMI calls to the server to perform SNMP functions. For example, the server can load MIB's and a client can avail the information in the MIBs without loading them each time it is started.

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

The following SNMP service interfaces are provided in the com.adventnet.snmp.rmi package. SnmpTarget SnmpRequestServer SnmpTrapReceiver SnmpPoller SnmpTable MibOperations

Examples of using these services are provided in the rmiclient directory.

AdventNet, Inc.

25

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

CORBA API Architecture


AdventNet SNMP API supports CORBA access to the SNMP API. For a typical non-CORBA or nonRMI client, you need the com.adventnet.snmp package classes in order to perform any SNMP operations, such as GET or SET. With CORBA and RMI packages, it is possible for a client to ask a server to perform these operations and obtain the result. A CORBA client needs the classes in com.adventnet.snmp.corba package to access these services. The CORBA IDL for the SNMP (corba.idl) is published as part of the AdventNet SNMP API package. One reason for providing the IDL file is that you can convert it into any other language mapping API and use it in the client application programs.

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 SNMPAPI 4 SNMPv2c :: Help Documentation

EJB API Architecture


AdventNet SNMP for EJB has been designed to support EJB applications, and conform to the EJB standards. The EJB standard restricts the Enterprise Java Bean from performing certain functions, such as socket access. In order to perform protocol operations, such as receiving traps while conforming to the EJB standard, an architecture suitable for SNMP operations for EJB is required. AdventNet SNMP API provides a solution to this. The protocol-specific functions needed by EJB components are provided by the SnmpEJBServer factory that runs outside the EJB container. This operates in a similar fashion to the SNMP RMI factory. This provides the SNMP protocol operations, such as accessing sockets, receiving traps, polling, and so on, which are not permitted in Enterprise Java Beans. These server functions are implemented using AdventNet's SNMP support for RMI. The Enterprise Java Beans use the SnmpEJBServer to create SNMP bean instances for protocol operations as required. These bean instances are used by the EJBs and garbage collected when the EJB instance is deleted, or when specifically de-referenced by the EJB. EJBs need to take of passivation, i.e. where the EJB is temporarily removed from memory and serialized to disk, because RMI references are not restored when the EJB instance is restored to memory. The EJB needs to use the JNDI to cache the RMI reference when it is being passivated. Future releases of AdventNet SNMP EJB will simplify this process and offer pooling of the SNMP bean instances. AdventNet provides the SNMP EJBs that can be used with this architecture. This release includes Session EJBs for synchronous SNMP operations and SNMP table support. More EJBs will be provided shortly. Application developers will build their own EJBs for specific SNMP-enabled applications, which can use the provided SNMP EJBs or directly use the SnmpEJBServer. The web container with JSP and Servlet pages connects to the EJBs to serve clients, as per the typical EJB Application Architecture. The HTML clients connect to the web container, which serves the HTML pages over HTTP. The Java clients may use the web container, but more often directly connect to the Session EJBs within the EJB container, using JNDI look-up and the home interfaces to get access to the EJB instances.

AdventNet, Inc.

27

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

The architecture for SNMP for EJB is illustrated below.

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

Development Environment for API


Setting Up for High-Level API Setting Up for Low-Level API Setting Up for RMI API Setting Up for CORBA API Setting Up for EJB API

This section explains the development environment needed for developing applications and applets using various APIs.

AdventNet, Inc.

29

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

Setting Up for High-Level API


The high-level API allows building more flexible applications, applets, and components that incorporate SNMP functions provided by the low-level API. The high-level API hides most of the SNMP and MIB details and is much more productive in building applications. The classes needed for developing applications and applets using the high-level API are provided by the com.adventnet.snmp.beans and com.adventnet.snmp.ui packages. The CLASSPATH should be set to AdventNetSnmp.jar and AdventNetLogging.jar in the <AdventNet/SNMPAPI/jars> directory. Applications developed using the high-level API should import the beans and the ui packages. If additional MIB support is required, the com.adventnet.snmp.mibs package should also be imported.

AdventNet, Inc.

30

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

Setting Up for Low-Level API


The low-level API allows the developer to work with all the details of SNMP and MIB. If developers are particular about reducing the size of the application or applet, the low-level API can be used. The classes needed for developing applications and applets using the low-level API are provided by com.adventnet.snmp.snmp2.usm and com.adventnet.snmp.snmp2.vacm packages that support SNMPv3. The CLASSPATH should be set to AdventNetSnmp.jar and AdventNetLogging.jar in the <AdventNet/SNMPAPI/jars> directory.

AdventNet, Inc.

31

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

Setting Up for RMI API


The classes needed for RMI client to access AdventNet SNMP API are provided by the com.adventnet.snmp.rmi package. The CLASSPATH should be set to AdventNetSnmp.jar, AdventNetLogging.jar, and AdventNetRMI.jar. The RMI interface and the implementation classes internally uses the high-level API. The RMI service interfaces very closely follow the SNMP beans classes in the com.adventnet.snmp.beans package. Therefore, the users do not have to bother about the underlying SNMP communication that is wrapped in the RMI classes. The steps involved in providing RMI access to SNMP services are: 1. Run the RMI registry. To start the RMI registry server, type the following command from the DOS prompt or UNIX shell. rmiregistry The above command starts the RMI registry listening at the default port 1099. 2. Type the following command to start the AdventNet RMI Server. java com.adventnet.snmp.rmi.SnmpFactoryImpl The above command binds the AdventNet RMI server with the RMI registry at the default port 1099. If the AdventNet RMI server starts successfully, a message 'Factory is ready' is displayed. Now, the AdventNet RMI server is ready to process the client requests. The SnmpFactoryImpl class has methods, such as createRequestServer, createTable, and createTarget that are used by the client applications to create the instances after getting the remote object handle. The client applications need to do the following. 1. Get the remote objects handle. com.adventnet.snmp.rmi.SnmpFactory factory = (com.adventnet.snmp.rmi.SnmpFactory) Naming.lookup("rmi:///AdventnetSnmpFactory"); The above code returns a remote interface object of type SnmpFactoryImpl class. 2. Invoke methods of the SnmpFactoryImpl class. com.adventnet.snmp.rmi.SnmpTarget target = factory.createTarget(); The above code creates a SnmpTargetImpl instance, which 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. A number of client examples are provided in the rmiclient directory, including an applet example. Start the rmiget client application example from the same host as follows. java rmiget localhost .1.3.6.1.2.1.1.1.0 The above command results in a GET operation to the localhost on the OID. If the localhost has a SNMP agent installed, you get the sysDescr message. Otherwise, a time out message is displayed.

AdventNet, Inc.

32

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

Setting Up for CORBA API


The classes needed for CORBA client to access the AdventNet SNMP API are provided in the com.adventnet.snmp.corba package. The CLASSPATH should be set to AdventNetSnmp.jar, AdventNetLogging.jar, and AdventNetCorba.jar. The CORBA interfaces and the implementation classes internally use the high-level API. Therefore, the users need not bother about the underlying SNMP communication that is wrapped in the CORBA classes. The Java files of the CORBA package are generated from corba.idl, available with the AdventNet SNMP package, using Sun's idltojava compiler. The idltojava compiler generates the respective stubs and skeletons for each interface declared in the corba.idl file. These stubs and skeletons are used by the server as well as the client-side code. For example, for the SnmpTarget interface in the corba.idl file, the following Java files are generated. _SnmpTargetImplBase.java _SnmpTargetStub.java SnmpTarget.java SnmpTargetHolder.java SnmpTargetHelper.java

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

Setting Up for EJB API


The SnmpTarget interface of the EJB API is used in the client application for performing many of the common operations, such as GET, GETNEXT, and SET operations. The EJB standard restricts users from performing certain protocol functions, such as socket access. The protocol-specific functions required by the EJB components are provided by an SnmpEJBServer factory that runs outside the EJB container. This operates in a similar fashion to the SNMP RMI factory. The SnmpEJBServer factory should be started within the EJB application server. Following are the jar files available in the <AdventNet_Home>\SNMPAPI\reference\ejb directory. std_MibOperationsEJB.jar std_SnmpTableEJB.jar std_SnmpTargetEJB.jar

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

Using MIBs in Applications


Loading MIBs Unloading MIBs Parsing MIBs Accessing Node Information Retrieving MIB Information Exceptions and Error Messages Database Schema Macro Type Constructs

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

Loading MIBs Directly


Applications can load the MIB modules directly from a file, URL or a Jar file. The MibOperations class in the MIB support API provides the methods necessary to load and unload MIB modules in the management applications and applets. If the application is developed using the low-level API, the MibOperations class has to be explicitly instantiated. If the high-level API or distributed API is used for building applications, the MibOperations class need not be instantiated. The following piece of code illustrates how applications use MibOperations to load MIB files. MibOperations mibops = new MibOperations(); try { mibops.loadMibModule("RFC1213-MIB"); } catch (Exception ex){ System.err.println("Error loading MIBs: " +ex); } The high-level and distributed APIs include built-in support for commonly used MIB operations and therefore the MibOperations class need not be explicitly called. However for advanced MIB support, the high-level APIs can get the handle of MibOperations using the getMibOperations() method. The following table lists the methods to be used for loading MIB files in the management applications and applets. API Name Class/Component Name API Method Remarks The loadMibModule method loads a MIB module from a file .or using the URL that specifies the location of the MIB module. The loadMibModules method loads a set of MIB modules specified by file names separated by space. This method loads the MIB modules specified by file names separated by space. A MIB file is loaded in a common place and is used by all the other Beans in that application or applet. - same as above - same as above - same as above -

MIB

MibOperations

loadMibModule(Applet, URL) loadMibModules(String) loadMibModules(Applet, String)

High Level

SnmpTarget SnmpRequestServer SnmpPoller SnmpTable

loadMibs(String)

SnmpTarget SnmpRequestServer SnmpTarget CORBA SnmpRequestServer 1. MibOperationsEJB EJB 2. SnmpTargetEJB RMI

loadMibs(String) loadMibs(String) 1. loadMibModule(String) 2. loadMibs(String)

AdventNet, Inc.

39

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

Factors to Consider While Loading MIB Files


1. The imported modules should be present in the current directory or the directory in which the MIB file is present. For example, the dependency file for the IF-MIB should be present in the same directory or in the current directory. 2. If the imported module is in a different directory, we can set the search path before loading the MIB. The search path can be set by using the method setMibPath(String). The API searches for the module in the path specified. Multiple paths can be given separated by a pipe(|) symbol. The following code snippet shows how to load a MIB file which has its dependency file in another directory. For example, if the IF-MIB is in mibs directory and if SNMPv2-MIB (dependency file for IFMIB) is in the patchmibs directory, the following code shows how to load IF-MIB. MibOperations mibops = new MibOperations(); try { mibops.setMibPath(" /home/mibs/ | /home/patchmibs/ "); mibops.loadMibModule("IF-MIB"); } catch (Exception ex) { System.err.println("Error loading MIBs: " +ex); } 3. The API can load MIB files with the extensions mib, txt,and my. The method setMibFileExtension(String) can be used to set the MIB file extension for the file to be loaded. Multiple extensions can be given separated by a space or a comma. Note that the extension names should not be cmi or cds because these extensions are reserved for loading compiled MIBs. Note: In 2.x releases, if the imported module is not found while parsing, the setThrowFileNotFound(boolean) method (now deprecated) controls whether a FileNotFound exception should be thrown by loadMibModule(). This should be not be used anymore because now it is mandatory that the imported modules should be present in the directory in which the MIB files are loaded.

Loading Multiple Revisions of MibModules


AdventNet SNMP API supports loading multiple revisions of MibModules. The setMultipleRevision(String revisionFileNames) method, is used for loading multiple revisions of MibModules, where the revision file names are given separated by a space or a pipe (|) symbol. If we want to load multiple revisions of RFC1213-MIB, file names of this revision modules have to be set. For example, if the multiple revisions of RFC1213-MIB are in the files RFC1213-MIB.txt, RFC1213-MIB.mib, etc. we have to set these file names using the following method. mibops.setMultipleRevision("../mibs/RFC1213MIB.txt|../mibs/RFC1213-MIB.mib"); After setting the multiple revisions, we should load these files explicitly. While loading, the file name is checked with the revisionFileNames we have set. If the file name matches, the modules are loaded with the names ModuleName+REVISION1, ModuleName+REVISION2, and so on. mibops.loadMibModules("../mibs/RFC1213-MIB.txt | .../mibs/RFC1213MIB.mib | ../mibs/RFC1213-MIB.my"); In this case, the modules will be loaded with the name of RFC1213-MIBREVISION1, RFC1213MIBREVISION2, RFC1213-MIB. We have not set the file RFC1213-MIB.my in the setMultipleRevision() method and therefore it is loaded with the name of RFC1213-MIB.

AdventNet, Inc.

40

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

Loading from Serialized Files


Applications can also save the MIB file as serialized Java objects and load from them. This reduces the loading time and enables distribution of serialized Java objects without distributing the MIB files. Serialization is not supported in applets.

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

The method getSerializedMibFileName()

can be used to get the serialized MIB file name.

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

Loading Compiled MIBs


AdventNet SNMP API allows loading of compiled MIB files. The compiled MIB files reduce the loading time considerably when compared to direct loading. This is because, the parsing and syntax validation is done only once and not every time the MIB file is loaded. Once the validation is done, the compiled file information is stored in a proprietary format. Next time when the MIB file is loaded, the syntax validation is avoided and the tree is constructed directly. This leads to performance improvement and more compact applications can be developed.

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

Loading from Database


AdventNet SNMP API allows loading MIB modules from the database. The MIB files can be stored in any RDBMS, such as MySql or Oracle. Applications can load these MIB files directly from the database.

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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.

Instructions to use MySql database for loading MIBs


The following database parameters are to be configured in the application. driver name - org.gjt.mm.mysql.Driver url - JDBC: mysql://<machine name>/<database name> username - <a valid user name> password - <password for the user>

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

Instructions to use Oracle database for loading MIBs


The following database parameters are to be configured in the application. driver name - org.jdbc.driver.OracleDriver url - JDBC:oracle:thin:@<machine name>:1521:<database name> username - <a valid user name> password - <password for the user>

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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.

Constructing the MIB Module into the Tree Structure


If parsing is completed successfully, the API resolves the parent and child nodes in the current module. If there are any unresolved nodes, it tries to load from the imported module that is defined in the IMPORTS section. If the unresolved object is not present even in the imported module, unresolved TC construct {objectName1, objectName2, ...} exception is thrown. Note: If the parsing level is NORMAL, SERIOUS, or CRITICAL, and if the MIB file contains errors, then the compiled files (cmi and cds files) or the serialized files (ser files) will not be created.

AdventNet, Inc.

51

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

Checks for Various Parsing Levels


The following tables describes the different levels of parsing that can be set and their corresponding checks. S. No 1 2 Level of Parsing Lenient Normal Checks No Checks Default checks Serious Checks Critical Checks Description This level is the default level accepting all types of MIB files. For example, it allows both SMIv1 and v2. This level conforms to the obsolete standards, such as RFC 1902, RFC 1903, etc. Most MIBs follow the obsolete standard. This level strictly follows the current standard. It accepts the constructs with interoperability and implementation problems. This level completely follows the SMIv1 and v2 standards. However, it does not accept the backward compatibility constructs, constructs with interoperability and implementation problems, etc.

Serious

Critical

Normal Parsing Level


When the parsing level is normal, the following checks are included. OBJECT_IDENTIFIER_CONSTRUCT CHECK_DEFAULT

Serious Parsing Level


When the parsing level is serious, the following checks are done in addition to Normal checks. IMPORTS_CONSTRUCT MODULE_IDENTITY_CONSTRUCT OBJECT_TYPE_CONSTRUCT TRAP_TYPE_CONSTRUCT NOTIFICATION_TYPE_CONSTRUCT TEXTUAL_CONVENTION_CONSTRUCT

Critical Parsing Level


When the parsing level is critical, the following checks are done in addition to Serious checks. AGENT_CAPABILITIES_CONSTRUCT OBJECT_GROUP_CONSTRUCT MODULE_COMPLIANCE_CONSTRUCT CHECK_IDENTIFIERS CHECK_MISCELLANEOUS

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

Accessing Node Information


When a MIB file is loaded using the Miboperations class, a MibModule instance is created to store the information about the module loaded from the MIB file. The MibModule class is used to restrict the MIB operations to a specific MIB module. Some methods are present in both the MibModule class and the MibOperations class. If a method in MibOperations is used, it is applicable for the node in all the MIBs loaded in the application. If a method in the MibModule class is used, it is restricted to that particular module. The MIB file is parsed and MibNode objects are created to store information about each node. The MibNode class represents a MIB node in a MIB module tree. It contains references to its parents and children and also to its dependents. The LeafSyntax class represents the syntax of a leaf node in a MIB module. The MibNode and the LeafSyntax classes provide the methods necessary to access the information on the nodes in the MIB file. Apart from this, the classes also provide the following functions to the management applets and applications. Ability to walk the loaded MIB modules as an ordered list of objects. Ability to access nodes with specific relationships to other nodes.

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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());

Ability to walk the loaded MIB modules as an ordered list of objects


The getNextLeafNode() in the MibNode class returns the next leaf node by searching through the current module. This is useful for agents or manager applications looking for the OID or label for the next MIB node for GETNEXT requests. This method spans multiple modules. The getIndexes(MibOperations) and getIndexNames() in MibNode class is used for getting the index name/node of the table. The getIndexNames() returns vector of indexes (as String) for the table when invoked on the entry node of the table. On the other hand, getIndexes() returns vector of indexes (as MibNode) when invoked on any of the column nodes except the entry node of the table.

Ability to access nodes with specific relationships to other nodes


Typically the relationship among the nodes are represented as parent-child or root-node because the MIBs are organized in an hierarchical format. The mibs package provides several methods that can be used to access the nodes with specific relationships. The method getParent() in the MibNode class gets the parent node of the current node and the method getChild(int subId) returns the child node corresponding to the particular subId. The getChildList() returns the nodes children as a vector. The methods getRootNode() and the getRootNodes() in the MibModule class is used to get a reference to the root node in the loaded MibModule. If a module contains a single root node, both the methods getRootNode() and getRootNodes() return the root node. If a module contains more than one root node, the getRootNode() method returns null and the getRootNodes() method returns a vector of root nodes. MibOperations mibops = new MibOperations(); MibModule mibmodule; MibNode node; Vector childnodes; mibmodule = mibops.getMibModule(your_mib_file_here); node = mibmodule.getRootNode(); childnodes = node.getChildList(); .. .. The methods isAncestorOf() and isDescendantOf() is used to check whether the nodes is an ancestor or descendant of the specified node. The getCommonAncestorWith(MibNode) method returns the common parent node of the selected MIB node.

AdventNet, Inc.

65

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

Retrieving MIB Information


Manipulating OIDs
The MibModule class enables operations on the loaded MIB modules. This class instance for a MIB module is obtained by loading the MIB through the MibOperations object. The translateToNames(String) method of the MibModule is used for translating numbered OID String to named OID String. The translateToNumbers(String) method is used for translating named OID String to numbered OID String. If the OID does not start with a dot, the standard prefix .1.3.6.1.2.1 is automatically appended and the OID String is returned. The getInstanceString(SnmpOID) method of MibOperations class gets the instance component of the OID as a String. Instances of scalar objects are identified by the OID value of the object suffixed with ".0". Instances of columnar objects are identified by their OID values suffixed by their index components. The getInstanceString(SnmpOID, MibNode) method of MibOperations class avoids having to search for node if already available. However, it is not ensured that a null is returned for a mismatched node. This returns the sub-string corresponding to the instance. For example, if the MibNode is system and the OID as sysDescr, the return value starts with the sub-id of mib-2. The intersection of the node OID and the given OID are eliminated from the returned OID string. The getNearestNode() method of MibModule class gets the nearest MIB node corresponding to the int array of the OID. The getNearestNode(SnmpOID) method of MibOperations class searches all MIB modules loaded in this MibOperations instance and returns the OID if found. The getSubID() of the MibNode class gives the sub identifier of this node's object-identifier. The ObjectIdentifier have the 128 sub-identifiers, each sub-identifier can have the value ranges from 0 to 4294967295. The getNumberedOIDString() method of the MibNode class gives the numbered OID string of the node. The getOID() method of the MibNode class gives the numbered OID of the node as an int array. The getOIDString() method of the MibNode class gives the named OID of the node. The getOIDVector() method of the MibNode class gets the named OID of the node as a vector. Processing MIB Information The createVariableBinding(String varName, String[] indexes, String value) method of the MibOperations class creates an SnmpVarBind instance with the supplied parameters. The method decodeInstanceString(String, Vector) of the LeafSyntax class decodes an instance string based on the instance and index nodes. The encodeInstanceString() method of the MibOperations class encodes an instance string based on the SNMP type of the index node. This encoded instance string should be concatenated to the node OID to get the complete OID. The encodeInstanceString() method of the LeafSyntax class encodes an instance string based on the index vector and index nodes. The createSnmpVarBind(Vector, SnmpVar, Vector) method of the MibNode class creates an SnmpVarBind instance with the supplied parameters. The method decodeDefval() of the MibNode class decodes the DEFVAL value that is defined for this node and returns the corresponding SnmpVar object.

Displaying MIB Information


To print the value in hex string format, you can use the toByteString() method. To print the values in the NVT ASCII format, the setIgnoreSpecificControlCodes(boolean) method of the MibOperations class can be to set true. If the value is between 32 and 127, the ASCII value is printed.

AdventNet, Inc.

66

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

Exceptions and Error Messages


The possible exceptions while loading a MIB are tabulated below. Possible Exceptions FileNotFoundException Reasons If the file is not found in the path specified, this exception is thrown. The cmi file can be loaded by setting loadFromCompiledMibs() to true. If set to false, we cannot parse the compiled MIB file and therefore the exception is thrown. When the cmi file is loaded, it internally loads the cds file. This exception is thrown when the cds file is loaded directly. The file name, if contains spaces, should be given within double quotes. If the quotes are not closed, this exception is thrown. The modules are searched in the path specified by the setMibPath() method. If the modules are not found, this exception is thrown. The imported MIB module name and its file name should be the same with any extensions. (except .cmi and .cds). The default extensions are .my, .mib, and .txt. Other extensions can be set using setMibFileExtension(). If any of the above conditions is not met, this exception is thrown. While loading MIBs from the corrupted compiled MIBs, this exception is thrown. Also, loading the MIBs compiled in older release version may throw this exception. While loading MIBs from serialized MIBs, the serialized MIBs are deserialized. If the stream is corrupted, this exception is thrown. This error may occur due to the incorrect parameters given to the initJdbcParams() method.

Could not parse the .cmi file

The .cds file could not be loaded.

Error parsing quoted filename Couldn't find file in search path specified

Imported file name and module name mismatch !

Couldn't open stream for cmiFile

Stream Corrupted Connection not established

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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.

The keyword was missing

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

Error Message

The 'INDEX' or 'AUGMENTS' keyword was missing in the table row object type construct which contains the sequence as {sequenceName}

Couldn't resolve these TC constructs : {TCObject, nodeObject ...}

Couldn't resolve these sequence constructs : {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.

Cyclic TC keyValue encountered in moduleName.

Was expecting a ModuleName and that should be in upper case or atleast in proper case

AdventNet, Inc.

71

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

Error Message

Encountered a reserved word reservedWord

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.

subOID value should not exceed 4294967295

AdventNet, Inc.

72

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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.

Module Table - Attributes


S. No Field Name 1 MODULENAME 2 3 4 RESOLVED OTHERROOTNODES TABLENAME Description The MIB module name. Indicates whether imports are successful. It takes the boolean value. Resolves the OIDs. The table name of each individual module.

Module Identity Table - Attributes


S. No Field Name 1 MODULENAME 2 MODITYNAME 3 4 5 6 7 8 LUPDATED ORG CONTINFO DESCR REVITEM OID Description The MIB Module Name. Specifies information about the MIB MODULE. The Last Updated field - Specifies the date and time at which the module was created or last modified. The Organization field - Gives information about the organization responsible for the module. The Contact Info field - Specifies the contact information of the person responsible for the module. The Description field - Explains the purpose of the module. The Revision field - Specifies the revision timestamp in the UTC format. The Object Identifier

AdventNet, Inc.

73

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

Textual Convention Table - Attributes


S. No 1 2 3 4 5 6 Field Name MODULETCNAME DISPHINT STAT DESCR REF TYPE Description The Module Textual Convention field - Specifies the name of the textual convention construct. The Display Hint field - Hints on how to display the value of the type or describe the sub-structuring of the value. The Status field - Specifies the status of the definition. The Description field - Describes of the node or item being defined. The Reference field - Specifies the source of the definition. Syntax of the base data type.

Trap Table - Attributes


S. No 1 2 3 4 5 6 Field Name MODULETRAPNAME ENTERPRISES VARIABLES DESCR REF TRAPTYPE Description The Module Trap Name field - Specifies the name of the TRAP-TYPE construct. The vendor identification for the network management subsystem that generated the trap. Specifies one or more scalar or columnar objects with values describing the event. The Description field - specifies information describing the status of the variables. The Reference field - Specifies the source of the definition. Gives the name of the trap.

Unit Table - Attributes


S. No Field Name 1 MODULENAME 2 OID 3 UNITVAL Description The MIB Module Name The Object Identifier Specifies the value of the Units field of the node object.

Node Table - Attributes


S. No Field Name 1 OID 2 NODENAME 3 MACROTYPE Description The Object Identifier The name of the leaf node. The name of the Macro type.

Object Type Table - Attributes


S. No 1 2 3 Field Name OID SYNT ACCSS Description The Object Identifier The Syntax field - Specifies the syntax of the data type. It should be one of the basic SNMP data types. The Access field - Specifies the allowed access to the leaf object.

AdventNet, Inc.

74

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

S. No 4 5 6 7

Field Name STAT DESCR REF DEFVAL

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.

Dependency Table - Attributes


S. No Field Name 1 DEPENDANTMODULENAME 2 IMPORTEDNODES Description Name of the imported module name. Information on the imported objects.

Agent Capabilities and Module Compliance Table - Attributes


S. No 1 OID 2 3 4 5 6 Field Name Description The Object Identifier The Product Release field - Describes the product release that includes the implemented capabilities. 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. Agent Capabilities Module and the Module Compliance Module Name.

PDTREL STAT DESCR REF ACMMCMNAME

Module Compliance Modules Table - Attributes


S. No Field Name 1 MCNAME 2 MCMNAME 3 4 MANDATORYGP GRPOBJ Description The Module Compliance Construct Name The Module Compliance Module sub-clause name The Mandatory Group field - Specifies a conditionally required object or notification group. The Group Object

Agent Capabilities Module Table - Attributes


S. No Field Name 1 ACMNAME 2 SUPPORTS 3 4 ACVINCLUDES ACVNAME Description The Agent Capabilities Module Name Specifies the module identifier. The AGENT CAPABILITIES VARIATION INCLUDES field - Specifies object and event groups that an agent implements. The Agent Capabilities Variation Name

AdventNet, Inc.

75

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

Agent Capabilities Variation Table - Attributes


S. No 1 2 3 4 5 6 Field Name ACMNAME ACVNAME SYNT WRITESYNT ACCSS CREAOBJ Description The Agent Capabilities Module Name The Agent Capabilities Variation Name The SYNTAX field The Write Syntax field The Access field - Specifies the allowed access to the leaf object The Creation-Requires field is used to document the objects that are required in a SET operation to create an instance of a row in a table. The DEFVAL clause is used to specify an acceptable value for a columnar object which may be used to create an instance of a row. The Description field - Describes the node or item being defined.

7 8

DEFVALCREAOBJ DESCR

Sequence Table - Attributes


S. No 1 2 Field Name SEQID SEQVAL Description The name of the table entry. The values in the Sequence construct.

Range List Table - Attributes


S. No 1 2 3 Field Name OID RANGE ENUM Description The Object Identifier The range value for the specified node. The enumerated values for the specified node

Object Group, Notification Group, Notification Type Table - Attributes


S. No 1 2 3 4 5 Field Name OID NAME STAT DESCR REF Description The Object Identifier The name of this Object 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.

AdventNet, Inc.

76

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

Macro Type Constructs


The MIB file can contain one or more MIB modules. Following are the macros defined in the SMIv1 and SMIv2. OBJECT IDENTIFIER OBJECT-TYPE

The following macro definition is defined only in SMIv1. TRAP-TYPE

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

For more information on textual conventions, refer Textual Conventions.

AdventNet, Inc.

82

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

Configuring SNMP Agent Parameters


SNMP Version Host Name Port Number Community Name Timeout and Retries Max Repetition Non Repeaters Trap Parameters

The above parameters are the common SNMPv2c parameters that need to be set while developing the applications and applets.

AdventNet, Inc.

83

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

SnmpSession SnmpPDU SnmpTarget SnmpRequestServer SnmpTarget SnmpRequestServer SnmpTargetEJB

setVersion(int)

RMI CORBA EJB

setSnmpVersion(int) setSnmpVersion(int) setSnmpVersion(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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

RMI CORBA EJB

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

SnmpTarget SnmpRequestServer SnmpPoller SnmpTable

Low-Level RMI CORBA EJB

SnmpSession SnmpPDU SnmpTarget SnmpRequestServer SnmpTarget SnmpRequestServer SnmpTargetEJB

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

Timeout and Retries


The timeout is the time interval that an application waits for a response message from an agent. Typically these values are given in milliseconds or in seconds. If the value is 5 seconds, the application waits for 5 seconds for the response before timing out. Retries are the number of times a request is sent when a timeout occurs. If the retry value is 0, the request is not re-transmitted during timeout. Applications differ in handling the non-zero retry value. Some applications handle it linearly. In other words, for every timeout, the retry count decrements by one and the request message is sent again. This cycle continues until a response is received or the retry count decrements to zero. Some applications will use the "exponential back off algorithm" for the timeout-retry counts. The timeout value grows exponentially if the retry value is non-zero. The timeout value doubles after each retry. For example, if the timeout value is set to 5 seconds and retry is set to 3, the first retransmission happens after 5 seconds, the second after 15 seconds, the next after 35 seconds, the next after 75 seconds, and so on. API Name HighLevel LowLevel RMI CORBA EJB Class/Component Name SnmpTarget SnmpRequestServer SnmpPoller SnmpTable SnmpSession SnmpPDU SnmpTarget SnmpRequestServer SnmpTarget SnmpRequestServer SnmpTargetEJB API Methods setTimeout(int) setRetries(int) setTimeout(int) setRetries(int) setTimeout(int) setRetries(int) setTimeout(int) setRetries(int) setTimeout(int) setRetries(int) Remarks

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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)

Low Level RMI CORBA EJB

setMaxRepetitions(int) setMaxRepetitions(int) setMaxRepetitions(int) setMaxRepetitions(int)

AdventNet, Inc.

90

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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)

Low Level RMI CORBA EJB

setNonRepeaters(int) setNonRepeaters(int) setNonRepeaters(int) setNonRepeaters(int)

AdventNet, Inc.

91

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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)

Generic and Specific Type


The SNMP standard defines seven traps that can be generated by SNMPv1 agents. Six of these traps are "generic" traps and the seventh trap is enterprise specific. The enterprise-specific trap is used by the private organizations to define their device-specific traps. The six generic trap types defined for SNMPv1 agents are as follows. coldStart trap (0) warmStart trap (1) linkDown trap(2) linkUp trap(3) authenticationFailure trap(4) egpNeighborLoss trap(5)

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

SMIv1 MIB Data Types


Data Type Name Description Specifies a value whose range may include both positive and negative numbers. Range = -2e31 to 2e31 - 1 (SMIv1 does not specify minimum or maximum values for the range). Examples: INTEGER INTEGER (0..127) -- corresponds to an unsigned 8-bit integer INTEGER (0..40 | 50 | 65 | 90..100) INTEGER (-2147483648..2147483647) -- corresponds to a signed 32-bit integer

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

Data Type Name TimeTicks

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

OBJECT IDENTIFIER IpAddress NetworkAddress

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

SMIv2 MIB Data Types

Data Type Name

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

Data Type Name

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

OBJECT IDENTIFIER IpAddress

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

Data Type Name

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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.

int value = 2143483508; SnmpInt snmpint = new SnmpInt(value);

AdventNet, Inc.

100

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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.

Retrieve Value from Variable


Using SnmpVar class Following are the methods of SnmpInt variable. class that are used to retrieve value from the created

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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.

int value = 2143483508; SnmpInt snmpint = new SnmpInt(value);

AdventNet, Inc.

104

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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.

Retrieve Value from Variable


Using SnmpVar Class Following are the methods of SnmpInt variable. class that are used to retrieve value from the created

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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.

Retrieve Value from Variable


Using SnmpVar Class Following are the methods of SnmpUnsignedInt created variable. class that are used to retrieve value from the

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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.

Retrieve Value from Variable


Using SnmpVar Class Following are the methods of SnmpGauge variable. class that are used to retrieve value from the created

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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.

Retrieve Value from Variable


Using SnmpVar Class Following are the methods of SnmpCounter variable. class that are used to retrieve value from the created

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

Retrieve Value from Variable


Using SnmpVar Class Following are the methods of SnmpCounter64 created variable. class that are used to retrieve value from the

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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.

SnmpTimeticks timeticks = new SnmpTimeticks(4294967295);

AdventNet, Inc.

124

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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);

Retrieve Value from Variable


Using SnmpVar Class Following are the methods of SnmpTimeticks variable. class that are used to retrieve value from the created

1. The getVarObject() returns the SnmpTimeticks value as Long object.

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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);

Retrieve Value from Variable


Using SnmpVar Class Following are the methods of SnmpString variable. class that are used to retrieve value from the created

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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.

Retrieve Value from Variable


Using SnmpVar Class Following are the methods of SnmpOID variable. class that are used to retrieve value from the created

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

Retrieve Value from Variable


Using SnmpVar Class Following are the methods of SnmpIpAddress variable. class that are used to retrieve value from the created

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

Retrieve Value from Variable


Using SnmpVar Class Following are the methods of SnmpString variable. class that are used to retrieve value from the created

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

Note: The value of year is in network-byte order.

Create Variable with DateAndTime Syntax


Using mibs package For creating a value for a node, the createVariable() method in the LeafSyntax class is used. The DateAndTime format value can be either 8 or 11 bytes. If the value is given in hex format, each octets should be separated by a colon and the value should be enclosed within single quotes. The following code snippet creates an SnmpVar object of DateAndTime type using the LeafSyntax class. String mibFile = "<mib name>"; String moduleName = "HOST-RESOURCES-MIB"; String nodeName = "hrSystemDate"; 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 = "2002-9-3,12:20:32.3,+5:30"; SnmpVar snmpvar = syntax.createVariable(value);

AdventNet, Inc.

148

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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.

Retrieve Value from Variable


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 "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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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);

Retrieve Value from Variable


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 "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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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 SNMPAPI 4 SNMPv2c :: Help Documentation

Data Retrieval Operations


SNMP GET SNMP GETNEXT SNMP GETBULK Polling Data

This section discusses the various data retrieval operations.

AdventNet, Inc.

153

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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.

Using High-level API


The SnmpTarget and the SnmpRequestServer beans of the high-level API are used in the applications and applets for performing the SNMP GET request. These beans are used for many of the common operations that are done with an SNMP agent, such as GET, GETNEXT, SET, and TRAP operations. The SnmpTarget bean is used for synchronous requests and the SnmpRequestServer bean is used for asynchronous requests. The SnmpTarget and SnmpRequestServer beans extends the SnmpServer class. The SnmpServer class maintains all the resources required for SNMP manager applications and applets. Some of the resources are SnmpAPI, SnmpSession, MibOperations, etc. provided by the low-level API. Most of the SNMP and MIB details are hidden for the user because the high-level API are built on top of the SNMP functions provided by the low-level API and therefore developing applications are simpler. Following are steps involved in performing a simple SNMP GET operation using the SnmpTarget bean. 1. Instantiate the SnmpTarget bean. SnmpTarget target = new SnmpTarget(); 2. Specify the mandatory parameters. //set the host in which the SNMP agent is running target.setTargetHost("localhost"); // set the OID target.setObjectID(".1.3.6.1.2.1.1.0"); 3. Set the SNMP version using the setSnmpVersion() method and perform an SNMP GET request to the SNMP agent. String result = target.snmpGet(); System.out.println("Response: "+result); View the complete example present in <SnmpGet.java>.

AdventNet, Inc.

154

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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.

Single variable request


To perform SNMP operations, we need to specify the Object ID that needs to be queried. The method setObjectID() is used for specifying the OIDs in the application. The OIDs can be given either in the numerical format or in the string format. If the OID does not start with a dot, it is prefixed by .1.3.6.1.2.1. Therefore, the OID 1.1.0 becomes .1.3.6.1.2.1.1.1.0. If the OID is given in the string format, we need to load the corresponding MIB file. For numerical OIDs, the MIB files need not be loaded. The method snmpGet() is used for performing SNMP GET operations. This method queries the host, specified in the setTargetHost(), for the OID, specified in the setObjectID(), and returns the SNMP variable as a string. The following methods can also be used to perform SNMP GET requests. snmpGetVariable() - returns an object of type SnmpVar. snmpGetVariableBinding() - returns an instance of SnmpVarBind. A variable binding has both the OID and the value.

Multi variable requests


We can also perform multiple OID queries in a single request by using the setObjectIDList() method. This method accepts an array of OIDs as arguments and performs the request for all the OIDs specified in the list. The method snmpGetList() is used for performing multiple OID requests. This method returns the list of data corresponding to the OIDs specified in the list. The following methods can also be used for performing SNMP GET requests with multiple OIDs. snmpGetVariables() - returns objects of type SnmpVar. snmpGetVariableBindings() - returns instances of SnmpVarBind. A variable binding has both the OID and the value.

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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.

Getting partial data while doing multi-variable requests


While making multi variable requests, the operation may fail even if one of the OIDs is invalid. However, the application can get the data from the valid OIDs by using the method setAttemptPartial(boolean)By default, this method is set to false. Setting it to true enables the application to get partial data from an agent during multiple variable requests. However, the invalid OIDs are returned with a value "null".

Using Low-level API


The SnmpAPI, SnmpSession, and SnmpPDU classes are used for most of the management operations in the low-level API. To use the communication services available with the API, we must instantiate and initialize SnmpAPI. The SnmpAPI class is a thread which monitors SNMP sessions and it contains various SNMP parameters. To communicate with SNMP entities, we need to instantiate the SnmpSession class. The open() method is 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. Following are the steps involved in performing a simple SNMP GET operation using the low-level API. 1. Instantiate the SnmpAPI class. SnmpAPI api = new SnmpAPI(); 2. Instantiate and open the SnmpSession class. SnmpSession session = new SnmpSession(api); session.open(); 3. The default protocol used for SNMP communications is UDP. Every packet that is sent through SnmpSession goes through the UDP implementation of SnmpTransportProvider. Parameters that are required for such operations are given through the UDPProtocolOptions class. After SnmpSession is opened for SNMP communication, the default values such as remoteHost and remotePort can be set using the UDPProtocolOptions object. If the remoteHost and remotePort is not specified in the SnmpPDU object, the API takes it from SnmpSession. An SnmpPDU instance needs to be created to send any request to an SNMP peer. The SnmpPDU provides most of the communication parameters related methods that are available with SnmpSession and it overrides the value in the session. Set the SNMP version using the setVersion() method and use the setCommand() method 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.

156

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

//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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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.

Using High-Level API


To perform the SNMP GETNEXT operation, the snmpGetNext() method can be used. Following are the steps involved in performing a simple GETNEXT operation using the SnmpTarget bean. //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.1.1"); //perform GETNEXT String result = target.snmpGetNext(); System.out.println("Response: " + result); The above code snippet performs a GETNEXT operation, with the SNMP agent running on localhost, to get the value of the variable 1.2. (sysObject ID) and displays the results. Note that it does not return the value of 1.1 but 1.2, the OID next to 1.1. View the complete example present in <tutorials/highlevelapi/SnmpGetNext.java>. The following methods can also be used for doing SNMP GETNEXT requests. snmpGetNextVariable() - returns an object of type SnmpVar. snmpGetNextVariableBinding() - returns an instance of SnmpVarBind. A variable binding has both the OID and the value.

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.

Using Low-Level API


Refer the topic SNMP GET Using Low-level API, which discusses the SNMP GET operation. To perform the SNMP GETNEXT operation, we need to use the GETNEXT_REQ_MSG command constant instead of GET_REQ_MSG.

AdventNet, Inc.

158

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

//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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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.

Using High-Level API


The additional parameters for the SNMP GETBULK operation can be set using the following methods. setMaxRepetitions(int) - the default value is 50. setNonRepeaters(int) - the default value is 0.

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

Using Low-Level API


Refer the topic SNMP GET Using Low-level API, which discusses the SNMP GET operation. The additional parameters for the SNMP GETBULK operations can be set using the following methods. setMaxRepetitions(int max_rep) setNonRepeaters(int non_rep)

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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 SNMPAPI 4 SNMPv2c :: Help Documentation

For polling multiple OIDs


The ObjectIDs that need to be polled can be set using setObjectIDList() method. Refer the following code snippet. poller.setObjectIDList(oids); ResultListener listener = new ResultListener() { public void setResult(ResultEvent evt) { for(int i=0;i<oids.length;i++) System.err.println("SnmpPoller Response: "+evt.getValue(i)); } }; poller.addResultListener(listener); The method evt.getValues() can also be used. This method will return a String array of polled data.

AdventNet, Inc.

163

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

Data Altering Operations


SNMP SET Setting Values for Datatypes

This section discusses the various data altering operations.

AdventNet, Inc.

164

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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.

Using High-Level API


To perform the SNMP SET operation, the snmpSet() method can be used. The following are the steps involved in performing a simple SNMP SET operation using the SnmpTarget bean. //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.1.5"); We need to load the MIB file to perform the SNMP SET operation. The MIB file is used to find the type of the object used in the SET operation. target.loadMibs("RFC-1213MIB"); To perform the SET operation, we need the OID, its type, and its value. If the corresponding MIB file is loaded, the API gets the type of the OID from it. If the MIB file is not available, we need to give the type of the OID. The following code shows a new value in the snmpSet() method. // perform SNMP SET String result = target.snmpSet("testing ...."); System.out.println("OBJECT ID: "+target.getObjectID()); System.out.println("Response: "+result); The above code performs a SET operation with the SNMP agent running on localhost to set the value of the variable 1.5. (sysName) to the new value "testing...." and displays the results. Note that the OIDs should have write access for performing the SET operations. View the complete example present in <tutorials/highlevelapi/SnmpSet.java>. The following methods can also be used for performing SNMP SET requests. snmpSet(value, type) - to perform set operations by giving both value and type. snmpSetVariable(Snmpvar var) - 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.

Multiple OIDs have to be set using the setObjectIDList() method and snmpSetList() should be used to query the agent.

AdventNet, Inc.

165

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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.

Using Low-Level API


The SnmpAPI, SnmpSession, and SnmpPDU classes are used for most of the management operations in the low-level API. To use the communication services available with the API, we must instantiate SnmpAPI. The SnmpAPI class is a thread which monitors SNMP sessions and it contains various SNMP parameters. To communicate with SNMP entities, we need to instantiate the SnmpSession class. The open() method is to be invoked to get the socket, SnmpTransportProvider, (DatagramSocket in case of UDP) for SNMP communication. Various parameters, such as remote host, remote port, version, community, retries, and timeouts can be set using this class. Following are the steps involved in performing a simple SNMP SET operation using the low-level API. Instantiate the SnmpAPI class. SnmpAPI api = new SnmpAPI(); Instantiate and open the SnmpSession class. SnmpSession session = new SnmpSession(api); session.open(); To perform SNMP SET operations, the command constant SET_REQ_MSG defined in the SnmpAPI class should be used. // Build set request PDU SnmpPDU pdu = new SnmpPDU(); pdu.setCommand(SnmpAPI.SET_REQ_MSG); To perform SET operations we need to know the OID, its type, and its value. These values are needed to build the varbind and can be received as user input. The variable binding or the varbind is the pairing of the OID and its corresponding value. This varbind should be added to the PDU for performing SET operations. The type of the variable can be INTEGER, STRING, COUNTER, etc. The SnmpAPI class provides constants for all the SNMP data types. Using this type, the value an instance of SnmpVar is created. String value = "localhost"; byte dataType = SnmpAPI.STRING; SnmpOID oid = new SnmpOID("1.5.0"); // sysName SnmpVar var = null; // create SnmpVar instance for the value and the type var = SnmpVar.createVariable(value, dataType); This SnmpVar object is used to create the varbind. //create varbind SnmpVarBind varbind = new SnmpVarBind(oid, var);

AdventNet, Inc.

166

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

Setting Values for Datatypes


The various values that are to be specified in a SET operation with respect to the SYNTAX of the object is given in the following table. Base Data Types or TCs INTEGER 100 Integer32 Unsigned32 OCTET STRING OBJECT IDENTIFIER NULL Counter 100 Counter32 Counter64 Gauge Gauge32 BITS STRING BITS {zero(0), one(1), two(2), three(3), four(4), five(5) } TIMETICKS IpAddress NetworkAddress OPAQUE 1995-9-21, 13:53:32.3, -7:0 DateAndTime or 995-9-21, 13:53:32.3 192.168.1.120/ 161 100 100 '64'h '64'h '64'h '54'h/'54'H or 54h/54H '50'h'/'50'H or '5'h/'50'H '64'h '1100100'b '010101000'b '010101'b 010101000b 010101b '1100100'b '1100100'b 100 adventnet 1.3.6.1.2.1.1.1.0 or 1.1.0 Value How to Set the Value Value in Hexadecimal '64'h '64'h Value in Binary '1100100'b '1100100'b

135 one three five one 3 five 100 192.168.1.220/ hostName 192.168.1.220/ hostName

'64'h '07:cb:09:15:0d:35: 20:03:2d:07:00' or '07:cb:09:15:0d:35: 20:03'

TAddress MacAddress

f1:f2:f3:f4:f5:f6

Refer Handling Datatypes for more information on datatypes.

AdventNet, Inc.

168

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

Traps and Notifications


Receiving Notifications Sending Notifications

This section discusses the various trap handling operations.

AdventNet, Inc.

169

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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.

Using High-Level API


The SnmpTrapReceiver bean in the high-level API is used to receive v1/v2/v3 traps. This bean listens for traps on a particular port. When a trap is received from an agent, it checks the trap version. If the trap received is a v3 trap, it performs a v3 authentication and fires a trap event to all the registered listener objects. The TrapEvent class contains the Trap-PDU. This trap event contains the trap data that is forwarded to the registered trap listener objects. The trap listener object then handles the received trap. To implement the Trap Listener interface and instantiate the SnmpTrapReceiver bean: public class SnmpTrapd implements TrapListener { SnmpTrapReceiver trapreceiver = new SnmpTrapReceiver(); The following code sets the port in which the trap is received and registers the trap listener. trapreceiver.setPort(162); trapreceiver.addTrapListener(this); // register the listener for trap events System.out.println("Waiting to receive traps ......."); The listener invokes the receivedTrap(TrapEvent) method when the trap is received by the TrapReceiver bean. The event TrapEvent contains the trap data. The traps can be received and results can be printed. View the complete example present in <tutorials/highlevelapi/ReceiveTrap.java>. The trap applications listen for traps in the default port (162). When a trap is received, the PDU information, such as agent address, trap type, etc. is printed. Traps can also be received in a different port other than 162 by using the -p option. In UNIX environment, port numbers below 1024 are reserved and can be used only by root (superuser). Therefore, if non-root users run the application, the following error message may be received. "java.net.BindException: Permission Denied" There are two ways to avoid this exception. One way is to login as root and run the program. The other way is to specify a port greater than 1023 using the -p option. For example, the following command listens for traps on port 2000. java snmptrapd -p 2000 However, we need to make sure that the port specified is not used by any other application. Otherwise the following exception is thrown.

AdventNet, Inc.

170

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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.

Using Low-Level API


There are two ways by which an application can receive an SNMP trap message. Using the callback() method in the SnmpClient interface Using the receive() method in the SnmpSession class

The interface SnmpClient is used by applications that wish to send and receive messages asynchronously. The SnmpClient interface implements callback, authentication, and debugging functions.

Receiving trap messages by using in SnmpClient


The interface SnmpClient is used by applications to send and receive messages asynchronously. The SnmpClient interface implements callback, authentication, and debugging functions. We implement SnmpClient in our main class. public class SnmpTrapd implements SnmpClient { We need to instantiate and start the SnmpAPI and open SnmpSession. We need to add the SnmpClient interface implementation to the session to invoke the callback, authentication, and debugging functions. By convention, the traps are received at the port 162. In this example, we set the local port to 8001 for receiving the traps. SnmpAPI api = new SnmpAPI(); SnmpSession session = new SnmpSession(api); SnmpPDU pdu = new SnmpPDU(); UDPProtocolOptions option = new UDPProtocolOptions(); pdu.setProtocolOptions(option); pdu.setLocalPort(8001); session.addSnmpClient(new SnmpTrapd()); session.open(); System.out.println("Waiting to receive traps in the port "+pdu.getLocalPort() +"......."); Now, we have to implement three methods of the SnmpClient interface.

AdventNet, Inc.

171

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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.

Using High-Level API


To send notifications, we can use the snmpSendNotification() method of SnmpTarget class. Following are the steps involved in sending notifications. //instantiate the SnmpTarget bean SnmpTarget target = new SnmpTarget(); target.settargetHost("hostname"); //set the Target Port on which the target host would be listening to receive traps. target.setTargetPort(162) //Set the SNMP version. target.setSnmpVersion(target.VERSION2C); //Set the community. target.setCommunity(community) //Set the oids for snmpTrapOID and sysUpTime //Send the SNMP v2 Trap String values[] = {"testing"} target.snmpSendNotification(1000,trapOID, values); View the complete example present in <tutorials/highlevelapi/Sendv2Trap.java>.

Using Low-Level API


Following are the steps involved in sending notifications. /Instantiate an SnmpPDU class SnmpPDU pdu = new SnmpPDU(); //Set the SNMP command on the SnmpPDU class as v1 trap SnmpAPI api = new SnmpAPI(); UDPProtocolOptions option = new UDPProtocolOptions(remoteHost); pdu.setProtocolOptions(option); //Build SNMPv2c trap pdu.setCommand(SnmpAPI.TRP2_REQ_MSG); //Add the Up time variable binding - mandatory SnmpOID oid = new SnmpOID(".1.3.6.1.2.1.1.3.0"); SnmpVar var = SnmpVar.createVariable(systemuptime, SnmpAPI.TIMETICKS); ... SnmpVarBind varbind = new SnmpVarBind(oid,var); pdu.addVariableBinding(varbind);

AdventNet, Inc.

174

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

//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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

Table Handling in Applications


SNMP Table Basics Fetching Tables Getting Row Data Getting Column Data Polling Table Data Table with Notaccessible Index Modifying Table Data Adding a Row Deleting a Row Other Table Operations

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

SNMP Table Basics


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. A scalar variable has a single instance and is identified by its ".0". On the other hand, a table object or the columnar variable can have one or more instances and is identified by its index value. To identify a specific columnar variable, the index of the row has to be appended to its OID. For example for a table with OID .1.3.6.1.2.1.x.x.xTable, with the column name yy and the index value ind1, the value of the column yy can be got by appending the instance ind1 to the columnar OID .1.3.6.1.2.1.x.x.xTable.xEntry.yy. If the table has multiple indices namely ind1 and ind2 then the value of the column yy can be got by using the OID .1.3.6.1.2.1.x.x.xTable.xEntry.yy.ind1.ind2. For example, consider tcpConnTable. It has four indices namely tcpConnLocalAddress, tcpConnLocalPort, tcpConnRemAddress, and tcpConnRemPort where the values of the table are as follows. tcpConnState listen(2) listen(2) listen(2) listen(2) established(5) established(5) closeWait(8) tcpConnLocalAddress tcpConnLocaPort tcpConnRemAddress tcpConnRemPort 0.0.0.0 21 0.0.0.0 0 0.0.0.0 23 0.0.0.0 0 0.0.0.0 3306 0.0.0.0 0 0.0.0.0 6000 0.0.0.0 0 127.0.0.1 1042 127.0.0.1 6000 127.0.0.1 6000 127.0.0.1 1042 192.168.1.78 1156 192.168.4.144 80

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.

Table with Implied Index


An index may be qualified by a modifier IMPLIED if the type of the variable is of varying length (e.g. OctetString or IpAddress or OID). If the index of a table is implied, then there is no need to specify the length of the instance variable. If the base type (SYNTAX) is IpAddress and the index is qualified by the modifier IMPLIED, the length of the instance is taken as 4.

AdventNet, Inc.

177

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

Tables with External Index


These tables are similar to the augmented tables which share the index values with other tables. However these are SMIv1 tables and augmented tables are SMIv2 tables.

Tables with EntryStatus and RowStatus Column


In an SNMP table, adding or deleting rows are possible only if the table has the EntryStatus column defined (if it is an SMIv1 table) or with the RowStatus column defined (if it is an SMIv2 table).

SMIv1 Tables with EntryStatus Column


The EntryStatus column is used to manage the creation and deletion of conceptual rows in SMIv1 tables. This represents the status of a table entry. The status column can have the following. 'valid(1)' - indicates that the row exists and is available for use. 'createRequest(2)' - supplied by the manager wishing to create a row. 'underCreation(3)' - indicates that the row is being created. 'invalid(4)' - supplied by the manager wishing to invalidate the corresponding entry.

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).

SMIv2 Tables with RowStatus Column


In SMIv2 tables, the RowStatus column is used to manage the creation and deletion of conceptual rows. This column has six defined values as follows. active(1) - indicates that the conceptual row with all columns is available for use by the managed device. notInService(2) - indicates that the conceptual row exists in the agent, but is unavailable for use by the managed device. notReady(3) - indicates that the conceptual row exists in the agent, one or more required columns in the row are not instantiated. createAndGo(4) - supplied by a manager wishing to create a new instance of a conceptual row and make it available for use. createAndWait(5) - supplied by a manager wishing to create a new instance of a conceptual row but not making it available for use. destroy(6) - supplied by a manager wishing to delete all of the instances associated with an existing conceptual row.

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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.

Using High-Level API


The table data can be retrieved using the SnmpTable bean of the high-Level API. The SnmpTarget, SnmpTableModel, TableBean, or SnmpTablePanel beans can be used for retrieving table data. The following section discusses on the retrieval of table data using SnmpTable and SnmpTarget class.

Using SnmpTable Retrieval Mode


The table data is retrieved by performing repeated SNMP GETNEXT or SNMP GETBULK operations. The SnmpTable bean, by default, uses the SNMP GETNEXT to retrieve the SNMP tables. For tables with less number of rows the GETNEXT operation proves efficient in fetching the values. To retrieve larger tables, the GETBULK mode is preferable. To use the GETBULK mode, the agent should either be SNMPv2c or SNMPv3. To set the retrieval mode to GETBULK, the following method of the SnmpTable class is used. table.setRetrievalMode(false); Setting the value of the above method to true allows the table to use GETNEXT to retrieve the table data. If the retrieval mode is set to false, we need to modify the Max-Repetitions value of GETBULK depending on the requirement. The following command sets the Max-Repetitions value to 60. table.setMaxRepetitions(60); The default value of the Max-Repetitions is 50. Depending on the table size and the maximum PDU size that the agent can handle, the Max-Repetitions value can be set. If the table size is not known, this can be set to an arbitrary value.

Retrieving Table Data


To retrieve the table data using the SnmpTable class, we need to know the OID of the table that is to be queried. The method setTableOID() uses this tableOID to get the table data. This method starts polling of table data automatically. The MIB containing the table has to be loaded in the application as follows. SnmpTable table = new Snmptable(); //instantiate SnmpTable table.setTargetHost("localhost"); // set the mandatory parameters table.loadMibs("RFC1213-MIB"); // load the MIB table.setTableOIDWoStart("ifTable"); //set the tableOID table.run(); // Fetches the data.

AdventNet, Inc.

179

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

Retrieving Partial Table


Partial table data can be viewed by setting only those columns that are needed to be fetched using setObjectIDList() method.

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>.

Using SnmpTarget class


The SnmpTable class is preferred to the SnmpTarget class for retrieve the SNMP table data. The SnmpTable class has additional table-related methods. To get the table data as

AdventNet, Inc.

181

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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.

Using Low Level API


To retrieve the table data using the low-level API, the SnmpAPI, SnmpSession, and SnmpPDU classes of the snmp2 package are used. The table data can be fetched by adding the columnOIDs(column names) of the table to the PDU and performing GETNEXT repeatedly. Following is the sample table. ID 3 6 8 12 managerHost localhost server printer switch managerPort 161 1030 8001 8080

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

Getting Row Data


Sometimes, the specifications require to fetch a particular row from a SNMP table. To retrieve a particular row from a table, the index value of the row should be known. To retrieve the row data from a SNMP table, both High-Level API and Low-Level API can be used.

Using High-Level API


Using SnmpTable Class The following methods in the SnmpTable class can be used for getting the row data from the SNMP tables. getRow(int rowPosition) - returns the specified row as an array of SnmpVarBind. Here, the parameter index specifies the position of the row in the table. efore calling this method, set the table OID using the setTableOIDWoStart(tableOID) method. getRow(String tableOID, String indexValue) - returns the row as an array of String. This method can be used if the table OID is known. Here, the parameter index specifies the instance value of the row in the table. ID 3 6 8 12 managerHost localhost server printer switch 161 1030 8001 8080 managerPort

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

SnmpTarget target = new SnmpTarget(); String str = {"id.6", "managerHost.6, "managerPort.6"}; target.setObjectIDList(str); String result [] = target.snmpGetList();

Using Low-Level API


To get the data of a row from the table, the OIDs (columnsOID.instance) can be added to the PDU using pdu.addNull(oids) and the request can be sent by setting the request command SnmpAPI.GET_REQ_MSG in the PDU. This fetches the data for the specified row. Consider the sample table. ID 3 6 8 12 managerHost localhost server printer switch 161 1030 8001 8080 managerPort

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

Getting Column Data


Similar to retrieving row data of a table, applications might also require to retrieve one or more column data. To retrieve a specific column or columns from a table, the columnOID of the row should be known. To retrieve the column data from a SNMP table, both High-Level API and Low-Level API can be used.

Using High-Level API


Using SnmpTable Class The following methods in the SnmpTable class can be used for getting the column data from SNMP tables. getColumn(int columnIndex) - returns the column data if the column index is given. getColumn(String columnName) - returns the column data if the column name is given.

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.

Using SnmpTarget Class


One or more columnOIDs have to be first set in the setObjectIDList() method of the SnmpTarget class. Then the snmpGetAllList() is used to fetch the entire column data. ID 3 6 8 12 managerHost localhost server printer switch managerPort 161 1030 8001 8080

AdventNet, Inc.

186

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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.

Using Low-Level API


If the data for a single column alone is required, the columnOID can be set in the PDU and request can be sent using session.syncSend() method. ID 3 6 8 12 managerHost localhost server printer switch managerPort 161 1030 8001 8080

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 SNMPAPI 4 SNMPv2c :: Help Documentation

Polling Table 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. In most cases, 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. If all the table data are required to be polled, SnmpTable class can be used. Use the following code snippet. table.setPollInterval(10); // sets the poll interval at which the table should be polled table.setTableOID("tableOID"); // sets the table OID and starts polling table.addSnmpTableListener(listener); // registers listener for table changes The table data is received in tableChanged() method. public void tableChanged(SnmpTableEvent e) { SnmpTable table = (SnmpTable)e.getSource(); if( e.isEndOfTable() || e.getType() == 2) { if (table.getRowCount() == 0) System.err.println("Error string: " + table.getErrorString()); return; } // print column names StringBuffer sb = new StringBuffer(); if (e.getFirstRow() == 0) { for (int i=0;i < table.getColumnCount();i++) sb.append(table.getColumnName(i)+" \t"); System.out.println(sb.toString()); } // print rows sb = new StringBuffer(); for (int j=e.getFirstRow();j<=e.getLastRow();j++) { for (int i=0;i<table.getColumnCount();i++) sb.append(table.getValueAt(j,i)+" \t"); } System.out.println(sb.toString()); } If only some columns in the table need to be polled, setColumnsPolled() method can be used to set the column OIDs that need to be polled. For example, if the columns first four columns of a table are needed to be polled: Vector index = new Vector(); index.addElement(new Integer("0")); index.addElement(new Integer("1"));

AdventNet, Inc.

188

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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 SNMPAPI 4 SNMPv2c :: Help Documentation

Table with Notaccessible Index


Sometimes while querying the SNMP table data, the index value of an SNMP table may not be returned. This is because the "MAX-ACCESS" value of the index entry is defined as 'not-accessible', in the MIB file. There can also be tables with more than one 'not-accessible' index columns. In all table-related classes, the columns with 'not-accessible' MAX-ACCESS are dropped and the request is sent only for the other columns. Therefore, the 'not-accessible' columns are not retrieved while retrieving tables. The getNotAccessibleIndex() method provided in SnmpTable class can be used to get the notaccessible indices. This method returns the not-accessible index values as a two-dimensional String array or null if the table has no column with not-accessible MAX-ACCESS. To get only the notaccessible column names, the method getNotAccessibleIndexColumns() can be used. This returns a String array of column names. Use the following code to get the values of not-accessible index. SnmpTable table = new SnmpTable(); table.setTableOIDWoStart("tableOID");//sets the tableOID table.run(); table.getNotAccessibleIndex(); //returns the not-accessible index values as a two dimensional String array. The SnmpTable class has another method getIndices() that can be used to get all the indices of the table. Example walk_indexes in the applications directory retrieves the values of the indices.

AdventNet, Inc.

190

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

Modifying Table Data


To set any value for a particular cell in the table, the row and column index should be known. The value can be set only if the data for the row, which contains the cell, is fetched by the table before a new value is set. To modify data in a SNMP table, both High-Level API and Low-Level API can be used.

Using High-Level API


The ID column represents the index column. ID 3 4 5 6 To set a new value to any cell: 1. Using SnmpTarget class The OID of the cell, the columnOID appended by the row index, is set using setObjectID() method. Then the snmpSet() method can be used to set the value. The following code snippet can be used to change the value of the cell 'switch' to a new value 'value' in the sample table. SnmpTarget target=new SnmpTarget(); target.setObjectID("managerHost.6"); target.snmpSet("value"); //sets the new value 2. Using SnmpTable class The following methods can be used to set a new value for a cell. void setValueAt(java.lang.Object aValue, int rowIndex, int columnIndex) or void setCellValue(String tableOID, java.lang.Object aValue, int rowIndex, int columnIndex) where the row and column index represent the position of the row and column in the table. The new value that needs to be set can be a String, SnmpVarBind or SnmpVar object. The following methods can be used to set the managerHost value 'switch'. table.setTableOID("tableOID"); table.setValueAt("newvalue", 3,1); or table.setCellValue("tableOID", "newvalue", 3,1) Here 3 represent the row position and 1 represents the column position in the table. For the managerPort value at 2nd row, 3rd column (1030), the row and column indices are 1 and 2 respectively. This value can be changed using setValueAt ("5000", 1, 2) or setCellValue ("tableOID", "5000", 1, 2). View the complete example present in <tutorials/highlevelapi/ModifyTable.java>. managerHost localhost server printer switch managerPort 161 1030 8001 8080

AdventNet, Inc.

191

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

Using Low-Level API


To set any value for a particular cell, the SnmpVarBind object with the OID of the cell, which is the columnOID appended by the row index for which new value has to be set, and the new value can be added to the PDU. Then the request can be sent using the syncSend() method in SnmpSession class. ID 3 4 5 6 managerHost localhost server printer switch managerPort 161 1030 8001 8080

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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.

Using High-Level API


The following method in the SnmpTable class can be used to add a new row to the table. addRow(boolean Status, String[] oidlist, String[] values) where Status - the rowStatus or entryStatus (default value is false indicating rowStatus) oidlist- the for the row to be added values - the values to be set in the row.

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

ID 1 2 3 4

managerHost localhost server printer switch

managerPort 161 1030 8001 8080

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>.

Using Low-Level API


To retrieve the table data using the low-level API, the SnmpAPI, SnmpSession, and SnmpPDU classes of the snmp2 package are to be used. For SMIv2 tables ID 3 6 8 12 managerHost localhost server printer switch managerPort 161 1030 8001 8080 rowStatus 1 1 1 1

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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.

Using High-Level API


The deleteRow(oid) method in the SnmpTable class can be used for deleting a row in the SNMP table, where oid is the status (either RowStatus or EntryStatus) column name appended by the index value of the row to be deleted. From SMIv2 tables The deleteRow(oid)method in the SnmpTable class can be used for deleting a row in the SNMP table. To delete a row in a SNMP table, the rowStatus value should be set to the value of 'Destroy(6)'. The deleteRow method does this internally and we need to give the rowStatus.index oid alone. The following method in the SnmpTable class is used to delete a row, where table is the instance of the SnmpTable class. table.deleteRow(rowStatus.indexvalue); ID 1 2 3 4 managerHost localhost server printer switch managerPort 161 1030 8001 8080 rowStatus 1 1 1 1

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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>.

Using Low-Level API


To retrieve the table data using the low level API, the SnmpAPI, SnmpSession and the SnmpPDU classes of the snmp2 package has to be used. For deleting a row from the table, the RowStatus (for SMIv2 tables) or the EntryStatus (for SMIv1 tables) column should be set to 6 and 4 respectively. For more information on rowStatus and EntryStatus refer the SNMP Table Basics section. From SMIv2 table To delete a row in an SNMP table with index 15, the rowStatus value for that row should be set to 'Destroy(6)'. The following command creates SnmpOID for the columnOID in the sample table where the numeric OIDs for the rowStatus column are.1.3.6.1.4.1.2.2.1.4. SnmpOID oid=new SnmpOID(".1.3.6.1.4.1.2.2.1.4.15"); The following command creates the SnmpVar object with the value and the type of the value. SnmpVar var = SnmpVar.createVariable("6",SnmpAPI.INTEGER);//6 refers to destroy. The following code snippet creates SnmpVariableBindings using this SnmpOID and SnmpVar and adds it to the PDU using addVariableBinding(). SnmpVarBind varbind = new SnmpVarBind(oid,var); pdu.addVariableBinding(varbind); Then perform session.syncSend(pdu) to delete the row with index 15 from the table. From SMIv1 table The procedure for deleting a row from the SMIv1 table is the same as the that of SMIv2 table. Note that the entryStatus value should be set to the value of 'Invalid(4)' to delete a row in a SMIv1 table. View the complete example present in <tutorials/lowlevelapi/DeleteRowSMIv2.java>.

AdventNet, Inc.

197

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

Other Table Operations


Apart from the table-related operations, the management applications is also required to handle the following situations. Identify the table name, given the OID. Identify the table index, given the OID.

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

Exceptions and Error Handling


Error Handling High-Level API Exceptions High-Level API Error Messages Low-Level API Error Messages

The various errors and exceptions that are generated while using AdventNet SNMP APIs are detailed in this section.

AdventNet, Inc.

199

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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.

User-defined Error Codes


Error codes between 1 and 18 are reserved for standard errors. Besides the standard error codes listed in the above table, SNMP API supports user-defined error codes. The addUserError(int code, String error) method is used to add user-defined error codes and the corresponding error strings. If the specified error code already exists, this method overwrites the previous string with the recent one provided. In case of user-defined error codes, the getErrorCode() method returns -2. The getErrorString(int) gets the error string corresponding to the specified error code. If the userdefined error string is not initialized, AdventNet-specific error is returned. If there is no AdventNetspecific error associated with the specified error code, null is returned. These methods are provided in ErrorMessages, SnmpTarget, and SnmpRequestServer classes.

AdventNet, Inc.

201

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

High-Level API Exceptions


The various exceptions that are thrown while using the AdventNet SNMP high-level API are tabulated below: S.No. Error Message Classes MibBrowser GraphDialog SnmpTablePanelUI TrapViewer MibBrowser MibBrowser GraphDialog MibBrowserUI MibBrowserUI When it occurs In these methods, the integer values are used either directly from arguments or after parsing to integer format. This exception is thrown due to the format of numbers. This is thrown if any of the class is not found inside the method. This is thrown due to databaserelated queries. This is thrown if the file name is not specified before query. This is thrown if the file is not found. This is thrown on IO errors.

NumberFormatException

2 3 4 5 6

ClassNotFoundException SQLException FileName not specified FileNotFoundException IOException

AdventNet, Inc.

202

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

High-Level API Error Messages


To catch and report SnmpErrors, AdventNet SnmpAPI defines the ErrorMessages class, which informs the user about the actual cause of error. These messages are set in the ErrorMessages class for the respective error codes. These messages can be changed by the user according to their requirement and can be thrown as output using the method getErrorString(). S.No. 1 Error Messages OID Not Specified Classes SnmpTarget SnmpRequestServer SnmpTable SnmpPoller SnmpTarget SnmpRequestServer SnmpTable SnmpPoller SnmpTarget SnmpRequestServer SnmpTable SnmpPoller SnmpTarget SnmpRequestServer SnmpTable SnmpPoller SnmpTarget SnmpTable SnmpPoller SnmpTarget SnmpTable SnmpPoller SnmpTarget SnmpRequestServer SnmpTable SnmpPoller SnmpTarget, SnmpRequestServer SnmpTable SnmpPoller SnmpTarget, SnmpRequestServer SnmpTable SnmpPoller SnmpTarget, SnmpRequestServer SnmpTable SnmpPoller SnmpRequestServer SnmpTarget SnmpTable SnmpPoller When it occurs This is set when the OIDs are not specified before making a request. This is also applicable for trapOID. This is set when the session's remote hostname is not specified in the request.

Session Remote Host Unknown. Security Exception connecting to remote host

This is set when the security exception is thrown while connecting to a remote host.

SNMP not initialized

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.

Invalid context Name

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

Low-Level API Error Messages


The following are the error messages that you could get while using AdventNet SNMP low-level API. S.No. 1 2 3 4 Error Messages Could not create security table Database not connected Could not create table Could not find SecurityProvider file Could not find Access Control Provider file When it occurs This is set when the specified class name may not be in the CLASSPATH or the classname is wrong. This is set when a database is accessed without connecting to it. This is set when unable to create the v3ConfigTable specified by the user. This is set when the "securityProvider.config" file is not present in the "conf" directory of AdventNet SNMP API package. This is set when the "acmProvider.config" file is not present in the "conf" directory of AdventNet SNMP API package. This is set when UnknownHostException is thrown because of the wrong local Address in SnmpSession or UDPProtocolOptions. This message is displayed when the open() method of SnmpSession is called after setting the local address using the method setLocalAddresses(String) of SnmpSession or UDPProtocolOptions. This is set when the protocol used is other than IP and the SnmpTransportProvider interface is not implemented and the class name is not specified in the "snmpTransport.config" file. This message is displayed if an error occurs in reading that file or creating an instance of the class specified. This error occurs when the open method of SnmpSession is called. This is set when there is problem in the open method after successful instantiation of the class specified in the snmpTransport.config" file.. This is set when the open method of SnmpSession is called with the GCJ_FLAG set to a value other that zero. Note: This GCJ_FLAG can be set in the snmp.properties file present in the "classes/com/adventnet/snmp/snmp2" directory. This is set when the send or syncSend method of SnmpSession is called without setting the remote host either on the PDU or on the session. This is set when the send or syncSend method of SnmpSession is called by setting an invalid remote host. This is set while trying to perform SNMPv3 AuthPriv query without editing the "java.security" file. When Cryptix package is used for encryption, the following command should be present in the "java.security" file. security.provider.2=cryptix.provider.Cryptix When SunJCE is used for encryption the following command should be present.

Cannot bind to address

Transport provider not configured

Error in open

Applet not supported

10

No remote IP address specified

11

Session Remote Host Unknown

12

Unable to encode PDU

AdventNet, Inc.

205

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

USMUserEntry: could not send a unknownUserNames report PDU

AdventNet, Inc.

207

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

USMUserEntry: could not send a wrongDigests report PDU

38

USMUserEntry: could not send a timeSync reply

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

Developing SNMP Application as Java Applet


Support Through SAS Extending SAS Support Through HTTP Applications of SAS API Installation Notes

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

Support Through SAS


SNMP Applet Server (SAS) allows the applet to send and receive SNMP packets to any managed device on the network. SAS provides communication for applets that are unable to connect directly to managed devices due to security limits. The SNMP requests made from the applet are passed onto SAS through TCP connection. SAS uses UDP to connect to the managed device and perform SNMP operations and pass the response back to the applet through TCP.

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

-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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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.

Provides a mechanism to receive traps


If applets wish to receive traps and notifications, they have to register with the SAS server. During registration, applets can specify the port on which the SAS server should listen for traps. The following piece of code illustrates how applets request the SAS server to deliver traps.

AdventNet, Inc.

213

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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.

Facilitates sending and receiving application-specific data


Applets can send their own data to server side application through the SAS server. The SAS server provides the SASessionClient interface for this purpose. Server side applications should implement the SASessionClient interface and register it with SAS server using the -session_client option available with the SAServer. The userSyncSend() method available in SASClient is used by applets to send data to server side applications. The following code illustrates how applets send their own data.

AdventNet, Inc.

215

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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.

Provides ability to resolve between internet hostnames and addresses


Applets can use getHostAddress() and the getHostName() methods available in SASClient class to map between IP address and hostnames. The getHostAddress() method resolves the host name to a dotted IP address with the help of the SAS server. The getHostName() method maps the dotted IP address to a fully qualified internet host name. pplets use these methods as follows. SASClient sasClient = session.getSASClient( ); String address = sasClient.getHostAddress(hostname, timeout); SASClient sasClient = session.getSASClient( ); String hostname = sasclient.getHostName(java.lang.String address, int timeout);

Provides ability to access databases


The following four methods are provided in SASClient to access the database. 1. connectDB(String driver, String url, String user, String password) This method is to set up the database connection. The jars or class files necessary for accessing database should be included in the CLASSPATH on the server side and not to be downloaded from the server. If the specified driver class is not present, this method throws an exception ClassNotFoundException. If the database connection with the specified url, user, and password is not established, an SQLException is thrown.

AdventNet, Inc.

216

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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.

public void init(String applet_dir, String webserver_rootDir);

public void initSession(InetAddress applet_addr, int applet_port, SASession session);

public int open(int port);

public SnmpPDU requestPDU(SnmpPDU pdu);

public SnmpPDU responsePDU(SnmpPDU pdu);

public byte[] clientCall(byte data[]);

public void closeSession(InetAddress applet_addr, int applet_port);

AdventNet, Inc.

218

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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.

public int open(int port);

public SnmpPDU requestPDU(SnmpPDU pdu); public SnmpPDU responsePDU(SnmpPDU pdu);

public byte[] clientCall(byte data[]);

public void closeSession();

public byte[] userCall(int reqType, byte data[]);

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

Support Through HTTP


SNMP communication through applets can also be performed using HTTP protocol. Though TCP/IP connection is more efficient than HTTP, HTTP access is required when we want to talk to a network with firewall restrictions.

Need for HTTP Tunneling


A firewall is a security mechanism that protects a private network being accessed from the public domain (the internet as a whole). It is typically implemented on a gateway device and protects the internal network from unauthorized access from outside the firewall. The firewall may also be configured to restrict the client's outside access. A firewall can be configured to restrict the types of protocols that may travel across the firewall and also the ports that these protocols access. Usually firewalls running on web servers are configured to allow only HTTP requests by enabling only the incoming requests on the default HTTP port 80 while blocking both incoming and outgoing requests on other ports. This allows the users outside the firewall to only browse web pages and access nothing else. It also blocks outside attempts inside the firewall to access the network. Normally, a client running an applet from outside the firewall cannot connect to the server due to the firewall restrictions. However, one way of bypassing this restriction and enabling Java applets to communicate with the servers is through HTTP tunneling. This is done is by creating servlets on the Java-enabled web server that listen for the requests from the client programs. The client request messages are embedded within HTTP request format because the server allows the HTTP requests to pass through the firewall. After the servlet module receives the HTTP request from the client, it strips the HTTP header information and processes the embedded SNMP request. Then the servlet module sends the SNMP request to the agent through UDP. On getting a response from the agent, it is passed back to the applet.

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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.

Limitations of Using HTTP protocol


Like most network protocols, HTTP uses the client-server model: An HTTP client opens a connection and sends a request message to an HTTP server. The server then returns a response message with the resource that was requested. After delivering the response, the server closes the connection, making HTTP a stateless protocol. Therefore, each resource to be retrieved requires its own connection. Opening and closing connections takes a substantial amount of CPU time, bandwidth, and memory. However, HTTP 1.1 uses persistent connections by default by allowing multiple transactions to take place over a single persistent connection thus ensuring faster response. However browsers, such as Netscape 4.x and IE 4.x use HTTP 1.0 that does not use persistent connection. As a result, using HTTP from applets is a bit slower than using TCP/IP.

AdventNet, Inc.

223

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

Tunneling support in AdventNet SNMP API


Applet support through HTTP in the AdventNet API is by means of servlets residing in the web server. HttpSnmpGWServlet is started with the web server used. The applet forwards the request to the 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 TCP/IP and HTTP for connecting the applet and the server (SAServer in case of TCP/IP and HTTPSnmpGWServlet in case of HTTP). For selecting between these two options, you have to specify the value for the parameter PROTOCOL in the HTML file. The changes to be made in the configuration file of the Tomcat web server to run HttpSnmpGWservlet is given in Installation Notes. HTTP provides the following. Ability to access SNMP data available with the devices in the network. Mechanism to receive traps. Ability to create/delete files and directories and save information on files, on the server.

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.

Provides a mechanism to receive traps


If applets wish to receive traps, they have to register with the SASClient. It is similar to receiving traps using SAS. Refer Support Through SAS.

AdventNet, Inc.

224

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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 SNMPAPI 4 SNMPv2c :: Help Documentation

Applications of SAS API


The applet or applications (SAS clients) can communicate with the SAS server using any transport protocol which communicates with the device using SNMP. This is done by implementing the SAS transport protocol and plugging it in the generic SAS transport provider framework. 1. SAS for bypassing applet security SAS can be used by applets to bypass the security restrictions imposed by the security manager in JDK 1.2 that doesn't allow applets (or any client, for that matter) to connect through the sockets on the unprivileged ports. The applet security restrictions mandate that applets are allowed to open a socket connections only to the address, where the hosting HTML page was downloaded. In other words, the Java applets cannot directly perform SNMP operations to other devices. Refer Support Through SAS for more details. 2. SAS for managing networks behind a firewall A firewall is a security mechanism that protects a private network being accessed from the public domain (the internet). Therefore, a client running an applet from outside the firewall cannot connect to the server for SNMP communication. However, one way of bypassing this restriction and enabling Java applets to communicate with the servers is through HTTP tunneling. Refer Support Through HTTP for more details. 3. SAS for implementing SNMP proxy The usage of SAS in this context becomes very clear when one thinks of using the SAS as an SNMP proxy to talk to SNMP enabled devices. This can be useful for remotely monitoring networks in a distributed way. In this scenario, the applications communicate with the SNMPenabled device (or agent) through the SAS module, which acts as an SNMP proxy to manage the SNMP-enabled device. The SNMP proxy acts as a manager and pro-actively monitors SNMP devices. When the SNMP proxy receives an SNMP request (GET, SET, or GETNEXT), it translates the request into SNMP requests. The proxy agent then sends the SNMP requests to the appropriate SNMP device. The SNMP device sends back the response message which the proxy sends to the system that made the original request. 4. SAS for managing SNMP networks in a secured way This application of SAS can be very useful if the user wants to manage the network in a secured manner. This can be done by using a secure protocol such as SSL between the SAS Client and the SAS server. Therefore the communication exists till the SAS server is completely secure beyond which the user has an option to use AdventNet's SNMPv3 API that provides security features for managing the SNMP-based network.

AdventNet, Inc.

226

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

AdventNet, Inc.

227

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

Using Transport Providers


SNMP Transport Providers SAS Transport Provider Custom Transport Provider Internet Protocol Version 6

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

SNMP Transport Provider


The SNMP transport provider is responsible for all communication between the SNMP manager and agent. It essentially acts as a bridge between the SNMP API and the actual transport protocol used. The advantage of using this approach is that the SNMP API need not be aware of the underlying protocol used and the user can virtually run SNMP over anything. For using a particular transport protocol, the user has to implement that protocol and plug-in (or register) it with the SNMP transport provider. Multiple protocols, such as TCP, UDP, and Serial communication can be used simultaneously in an application to communicate with various agents having SNMP over different protocols. The corresponding protocol providers are to be implemented by the user. We have provided simple command-line examples that use the TCP/IP protocol over SNMP transport provider to perform basic operations, such as GET, SET, GETNEXT, GETBULK, TRAPS, INFORM, and WALK. Also command-line example has been provided that performs SNMP GET operation with UDP/IP and SNMP GETNEXT operation with TCP/IP protocol.

APIs used for plugging-in your protocol implementation


These interfaces are part of the com.adventnet.snmp.snmp2 package. 1. SnmpTransportProvider - This interface provides the basic I/O operations. It contains the following API methods. Refer the javadocs files for exact syntax. open - Opens the transport interface over which the data is sent/received. close - Closes the transport interface after communication is over. read - Receives data from the peer over the transport interface. write - Sends data to the peer over the transport interface.

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

SAS Transport Provider


The SAS API uses TCP as the default transport protocol and also supports HTTP protocol. Apart from this, it also uses the protocol-independent transport provider for SAS communication, where the users can plug-in their own transport protocol between the SAS Client and the SAS server. The transport provider is responsible for all communication aspects between the client and server and interfaces with the SNMP API to communicate. 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 transport protocol, 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.

APIs for the SAS transport implementation


These interfaces are part of the com.adventnet.management.transportpackage. 1. SessionTransportProvider - This interface provides the basic IO operations. It contains the following API methods: (Refer the Javadocs for the exact syntax) open() - Opens the transport interface over which the data is sent/received. close() - Closes the transport interface after communication is over. read() - Receives data from the peer over the transport interface. write() - Sends data to the peer over the transport interface.

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

Custom Transport Provider


How to plug in your protocol implementation in the SNMP transport provider framework
1. Provide implementation of SnmpTransportProvider - This class provides the open, close, read, and write implementation required for TCP/IP communication. This can be used to set up the basic communication between the SNMP entities. Reference Implementation is provided for TCP. 2. Provide implementation of ProtocolOptions - This class provides the necessary parameters needed for the protocol communication, such as the host, port etc. for TCP/IP. In case of the SNMPv3 module, this class contains the implementation of getSessionId. This is used by the v3 module to uniquely identify each session connection between the SNMP entities. Therefore for TCP/IP, this can be a combination of the destination host and port. Reference implementation provided for TCP. 3. Provide a configuration file snmpTransport.config that contains the name of the implemented SnmpTransportProvider class. Reference file for TCP is provided in the <conf> directory. Note: In the application, the following points should be taken care of while using the transport provider framework.(For actual implementation details, see examples for SNMP GET, SET, etc. for TCP/IP.) After creating the session object, set the protocol to SnmpSession.TRANSPORT_PROVIDER using setProtocol method. We provide UDP/IP as the default protocol. Create a ProtocolOptions object with the necessary parameters. Set this on the session object using setProtocolOptions method. In case of V3 module, getSessionId should be passed as parameter instead of remotehost and remoteport (which is done in UDP/IP) in the init_v3_params method. It is mandatory for all the protocol options to be set first on the SnmpSession object before opening the session.

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

Internet Protocol Version 6


AdventNet SNMP API 4 supports transport of SNMP packets over UDP/IPv6 and TCP/IPv6. It makes use of the IPv6 socket APIs provided by JDK1.4. The transport provider framework of SNMP API hides the details of the IPv6 communication from the user. The users have to just specify the IPv6 address of the IPv6 node with which they wish to communicate in SnmpPDU or as a Target Host parameter in the classes (such as SnmpTarget, SnmpPoller, etc.). The communication with the agent is handled by the default UDP (or TCP) transport provider implementations using the IPv6 socket API provided by JDK1.4 and above. Following is a brief introduction about IPv6 and the address formats. It also describes about the IPv6 support in the Sun's J2SDK/JRE1.4. This provides an understanding of IPv6 addressing formats and how it can be specified through the SNMP APIs.

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.

Representation of IPv6 Addresses


There are three conventional forms for representing IPv6 addresses as text strings. The preferred form is x:x:x:x:x:x:x:x, where the 'x's are the hexadecimal values of the eight 16-bit pieces of the address. Examples: FEDC:BA98:7654:3210:FEDC:BA98:7654:3210 1080:0:0:0:8:800:200C:417A Due to some methods of allocating certain styles of IPv6 addresses, it will be common for addresses to contain long strings of zero bits. In order to make writing addresses containing zero bits easier a special syntax is available to compress the zeros. The use of "::" indicates multiple groups of 16-bits of zeros. The "::" can only appear once in an address. The "::" can also be used to compress the leading and/or trailing zeros in an address. Examples: 1080:0:0:0:8:800:200C:417A a unicast address FF01:0:0:0:0:0:0:101 a multicast address 0:0:0:0:0:0:0:1 the loopback address 0:0:0:0:0:0:0:0 the unspecified addresses

AdventNet, Inc.

234

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

IPv6 in J2SDK/JRE 1.4


With the J2SDK/JRE 1.4 release, IPv6 support has been added to Java Networking. This makes J2SE compliant with the following standards (RFCs). RFC2373: IPv6 Addressing Architecture; RFC 2553: BasicSocket Interface Extensions for IPv6; RFC 2732: Format for Literal IPv6 Addresses in URLs.

Supported Operating Systems


The following operating systems are supported in this release. Solaris 8 and above Linux kernel 2.1.2 and above (RedHat 6.1 and above) Windows XP with JDK 1.5

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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.

InetAddress Class Changes


This class represents the IP address. It provides address storage, name-address translation methods, address conversion methods, as well as address testing methods. In J2SE 1.4, this class is extended to support both IPv4 and IPv6 addresses. Utility methods are added to check address types and scopes. The two types of addresses, IPv4 and IPv6, can be distinguished by the Java type Inet4Address and Inet6Address. When IPv6 is used, all the methods in AdventNet SNMP API that return the InetAddress under IPv4, will return the Inet6Address.

AdventNet, Inc.

236

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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 SNMPAPI 4 SNMPv2c :: Help Documentation

Using High-Level API


The following are the steps involved in enabling the internationalization support to the applications and applets developed using the high-level API. 1. The MibBrowser.properties file available in the <MibBrowser> directory has to be used as the template file. This file contains the English strings of all the GUI labels and the messages. 2. The MibBrowser.properties file has to be copied to the specified locale file. For example, if the application or applet that is being developed is to be displayed in French, the MibBrowser.properties has to be copied as MibBrowser_fr_FR.properties file. The language and country are to be represented by the standard two-letter codes (fr - French and FR - France). 3. The developer has to write the equivalent strings of the chosen language and country in this file. This enables the application to print the user-written strings instead of the English strings. The default English strings is used for strings for which corresponding locale specific strings are not given. 4. After the above steps, the code changes related to internationalization has to be done in the application or applet source file. The SnmpUIUtils class present in com.adventnet.utils package has to be used for this purpose. 5. The field Internationalize of the SnmpUIUtils class should be made to true for internationalizing the API. By default it is false. This should be set to true before instantiation. SnmpUIUtils.INTERNATIONALIZE = true; 6. Using the method setLocale(Locale) of the SnmpUIUtils class, the locale should be first set. The properties file should be edited with proper localized strings. SnmpUIUtils.setLocale(new Locale("fr","FR")); 7. The UI components (menus, dialogs, etc) display the default font, if it is not supported by the specified locale. Otherwise, the font that supports the specified locale has to be set using the setFont(Font) of the SnmpUIUtils class. 8. The bundle name can be set using the method setBundleName(String) of the SnmpUIUtils class. The bundle name can be specific to the application and the file name of the properties file should be the same as the bundle name with proper locale extended. For example, you can have the bundle name LineGraphBean for an application using LineGraphBean. If the localization was done for Tamil language of country India (ta_IN), the properties file should be named as LineGraphBean_ta_IN.properties. SnmpUIUtils.setBundleName("LineGraphbean"); Note: If the locale and the bundle name are not set, the default properties file, MibBrowser.properties, is used to implement internationalization. 9. The method setSearchPath(String) of the SnmpUIUtils class can be used to get the properties file present in other directories. By default, the properties file is searched in the directory in which the application is executed. The path can be set using the above method. In case of applications, the path can be absolute or relative while with applets the path should be relative to the applet document base. SnmpUIUtils.setSearchPath("< path of the properties file >" ); 10. Now we can instantiate the bean. In case of applets, the Applet instance should be passed to the SnmpUIUtils class using the method setApplet(Applet). SnmpTarget target = new SnmpTarget(); The source files have to be compiled and regenerated to reflect these changes. Now if the application or applet is executed, it has the user-defined strings instead of the default English strings.

AdventNet, Inc.

238

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

Using Low-Level API


The following are the steps involved in enabling the internationalization support to the applications and applets developed using the low-level API. 1. The MibBrowser.properties file available in the <MibBrowser> directory has to be used as the template file. This file contains the English strings of all the messages. 2. The MibBrowser.properties file has to be copied to the specified locale file. For example, if the application or applet that is being developed is to be displayed in French, the MibBrowser.properties has to be copied as MibBrowser_fr_FR.properties file. The language and country are to be represented by the standard two-letter codes (fr - French and FR - France). 3. The developer has to write the equivalent strings of the chosen language and country in this file. This will enable the application to print the user-written strings instead of the English strings. The default English strings is used for strings for which corresponding locale specific strings are not given. 4. After the above steps, the code changes related to internationalization has to be done in the application or applet source file. The SnmpUtils class present in com.adventnet.utils package has to be used for this purpose. 5. The field Internationalize of the SnmpUtils class should be made to true for internationalizing the API. By default, it is false. This should be set to true before instantiation. SnmpUtils.INTERNATIONALIZE = true; 6. Using the method setLocale(Locale) of the SnmpUtils class, the locale should be first set. The properties file should be edited with proper localized strings. SnmpUtils.setLocale("fr","FR"); 7. The bundle name can be set using the method setBundleName(String) of the SnmpUtils class. The bundle name can be specific to the application and the file name of the properties file should be same as the bundle name with proper locale extended. For example, you can have the bundle name SnmpSession for an application using SnmpSession. If the localization was done for Tamil language of country India (ta_IN), the properties file should be named as SnmpSession_ta_IN.properties. SnmpUtils.setBundleName("SnmpSession"); Note: If the locale and the bundle name are not set, the default properties file, MibBrowser.properties, is used to implement internationalization. 8. The method setSearchPath(String) of the SnmpUtils class can be used to get the properties file present in other directories. By default, the properties file is searched in the directory in which the application is executed. The path can be set using the above method. In case of applications, the path can be absolute or relative while with applets the path should be relative to the applet document base. SnmpUtils.setSearchPath("< path of the properties file >" ); 9. Now, we can instantiate our class. In case of applets, the Applet instance should be passed to the SnmpUtils class using the method setApplet(Applet) of the SnmpUtils class. SnmpSession session = new SnmpSession(); The source files have to be compiled and regenerated to reflect these changes. Now if the application or applet is executed, it has the user-defined strings instead of the default English strings.

AdventNet, Inc.

239

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

Logging Management Applications


Logging Mechanism

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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.

Logging debug and error messages


Using this feature, applications can log the following messages while querying for one or more variables from the remote agent. Debug messages Error messages

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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){ ...... } }

Logging the actions performed in the application


Using this feature, applications can log various actions that take place during the processing of SNMP request. This would come in handy for various purposes like pinpointing bugs, performance blockades etc. Messages can be logged in a file based on the severity level (Log Level) based on modules like logging only for mibs package (or) beans package etc.

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

Deploying EJB Applications


The examples provided with AdventNet SNMP API are for one of the following application server.

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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.

Deployment in Weblogic 7.0


The following are the steps involved in deployment and usage of AdventNetSNMP EJB jar in WebLogic 7.0 edition.

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.

Steps to start the SnmpStarter class with the WebLogic server


1. Ensure the standard settings are performed. 2. Compile the SnmpStarter.java at <AdventNet\SNMPAPI\reference\ejb> directory. Create a jar file, say SnmpStarter.jar, with the compiled SnmpStarter.class. Example: javac SnmpStarter.java -d temp From the tempdirectory execute the following. jar -cvf SnmpStarter.jar com 3. Add the following line in the config.xml file.(<WebLogic_HOME>\samples\server\config\examples directory). <StartupClass ClassName="com.adventnet.snmp.weblogic.SnmpStarter" FailureIsFatal="true" Name="SnmpEJBServer" Targets="examplesServer"/> 4. Now, run the script startWLS.bat file (at <WebLogic HOME>\server\bin directory). This starts the SnmpStarter class with the WebLogic server.

Steps to run the client examples


1. Ensure the standard settings are performed, EJB bean is deployed successfully, and the SnmpStarter class is running. 2. Now, run the client examples (present in <AdventNet\examples\ejbclient> directory). Example:java ejbget localhost 1.1.0 The above command fetches the data successfully.

AdventNet, Inc.

249

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

Deployment in Weblogic 6.1 Beta


The following are the steps involved in deployment and usage of AdventNetSNMP EJB jar in WebLogic 6.1 beta edition.

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.

Steps to start the SnmpStarter class with the WebLogic Server


1. Ensure the standard settings are performed. 2. Compile the SnmpStarter.java present in <AdventNet\SNMPAPI\reference\ejb> directory. Example: javac SnmpStarter.java -d temp 3. Add the following line in the config.xml file.(<WebLogic_HOME>\config\mydomain directory) <StartupClass ClassName="com.adventnet.snmp.weblogic.SnmpStarter" Name="SnmpEJBServer" Targets="myserver"/> 4. Now, run the script startWebLogic.cmd. This starts the SnmpStarter class with the WebLogic server. /p>

AdventNet, Inc.

250

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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.

Steps to run the client examples


1. Ensure the standard settings are performed, EJB bean is deployed successfully and the SnmpStarter class is running. 2. Now, run the client examples (<AdventNet\SNMPAPI\examples\ejbclient> directory). Example: java ejbget localhost 1.1.0 The above command fetches the data successfully. For further information on using weblogic.ejbc and weblogic.deploy, refer the following URLs. http://e-docs.bea.com/wls/docs61/ejb/EJB_utilities.html#1075296 http://e-docs.bea.com/wls/docs61/ejb/EJB_deployover.html

Deployment in Weblogic 5.1


The following are the steps involved in deployment and usage of AdventNetSNMP EJB jar WebLogic 5.1 edition.

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.

Steps to start the SnmpStarter class with the WebLogic server


1. Ensure the standard settings are performed. 2. Compile SnmpStarter.java at <AdventNet\SNMPAPI\reference\ejb> directory. Example: javac SnmpStarter.java -d temp 3. Edit the weblogic.properties file in <Weblogic-Home> directory. weblogic.system.startupClass.SnmpEJBServer=com.adventnet.snmp.weblogic.Snmp Starter 4. Now, run the scriptstartWebLogic.cmd. This starts the SnmpStarter class with the WebLogic Server.

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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.

Steps to run the client examples


1. Make sure the standard settings are performed, EJB bean is deployed successfully, and the SnmpStarter class is running. 2. Now, run the client examples (at <AdventNet>\SNMPAPI\examples\ejbclient directory). Example: java ejbget localhost 1.1.0 The above command fetches the data successfully.

AdventNet, Inc.

252

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

Setting Up the Environment


Using Applications Running Applets

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

Running RMI Examples


The <rmiclient> directory contains examples for using the RMI Client APIs in AdventNet SNMP package. The APIs allow remote RMI clients to access SNMP services through a server that performs the SNMP operations.

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.

Running CORBA Examples


The <corbaclient> directory contains examples of using the CORBA Client APIs in AdventNet SNMP API. The APIs allow the remote CORBA clients to access the SNMP services through a server that performs the SNMP operations.

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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.

Running EJB Examples


The examples provided with the AdventNet SNMP API are for a specific application server. i.e. BEA Weblogic Server 5.1. This application server is one of the many EJB capable application servers in market place. These examples can easily be migrated to other EJB application servers by simply changing imports for JNDI. Only the SNMP server startup class needs to be modified for each application server. Future releases of AdventNet SNMP API will provide instructions on using other application servers. While using the EJB examples available in the <examples/ejbclient> directory, the client applications must set the CLASSPATH to AdventNet EJB classes and AdventNetSnmp.jar, before setting it to the application servers classes.

AdventNet, Inc.

257

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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 SNMPAPI 4 SNMPv2c :: Help Documentation

Data Retrieval Examples


SNMP GET SNMP GETNEXT SNMP GETBULK SNMP Walk

This section discusses the various examples for retrieving data.

AdventNet, Inc.

259

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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 SNMPAPI 4 SNMPv2c :: Help Documentation

Data Altering Examples


SNMP SET SNMP SET Without Using MIB

This section discusses the various examples for altering variables.

AdventNet, Inc.

265

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

SNMP SET Without Using MIB


The snmpset_without_mib example 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 in a remote host where the agent resides, we need to specify the OID, the data type, and the value to be set. In the previous example, the datatype is taken from the loaded MIB file. In this example, instead of loading the MIB file, we will specify the data type explicitly. For example: java snmpset_without_mib localhost 1.5.0 STRING testing The above command performs a SET operation with the SNMP agent running on localhost to set (write) the value of the variable 1.5. (sysName) to "testing". To check the new value we can do the snmpget and see the new value being retrieved. Unlike the previous example we are not loading the MIB file here, because we are specifying the type of the OID.

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

Notification and Inform Examples


Trap Receiver Send Notification Send Inform Request Send v2c Inform Receive v2c Inform

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

[-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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

Send Inform Request


The sendinform example is used to send v2c and v3 inform requests. The inform requests can be sent from a manager to another manager. To send the v2c/v3 inform request, 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.

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

Send v2c Inform


The snmpv2cinformreq example can be used to send v2c inform requests. 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.

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

Receive v2c Inform


The snmpv2cinformreqd example can be used to receive v2c inform requests. 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.

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

Table Handling Examples


Retrieve Table - Non-UI Retrieve Table - UI Walk Indexes Get By Index Set Table Value Encode Table Index Get Column Get Row Get Table Info SNMP CORBA

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

Table Retrieval - Non UI


High Level API RMI API CORBA API EJB API

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

The screen shot of largetable example is given below.

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

The screen shot of tableSettingsDemoAppn example is given below.

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

The screenshot of this applet example is given below.

Refer the source code for the tableSettingsDemo example present in <examples/uiapplications/tableSettingsDemo.java> for more information.

AdventNet, Inc.

285

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

Set Table Value


The setTableValue example is used to set the value of a particular cell of the table.

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

Encode Table Index


The encodeTableIndex example is used to get all the column OIDs of the table with appended index (instance) values. This example encodes the index if it is of type octetstring.

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

Get Table Info


The getTableInfo example is used to get the information about an SNMP table.

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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 SNMPAPI 4 SNMPv2c :: Help Documentation

MIB Handling Examples


MibNode Details Leaf Node Details JFC MIB Tree

This section explains some of the examples related to MIBs.

AdventNet, Inc.

294

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

MIB Node Details


This is a sample application illustrating how to use the MibOperationsEJB to load MIBs and get the corresponding node details for the MibNode specified by the user. The following command runs the application. java ejbNodeDetails -m mibs\RFC1213-MIB sysDescr The above command loads the RFC1213 MIB and retrieves the node details of sysDescr and prints them. For example, this example prints the following details. syntax | Access| Status | OID | Node| Description To run the ejbNodeDetails application from another host where the application server runs, you can use the following command. java ejbNodeDetails -EJBServer SERVER -m mibs\RFC1213-MIB sysDescr It is assumed that the application server runs on a machine SERVER and you want to get the node details on the server itself. The argument "localhost" specifies that ejbNodeDetails operation is performed on the "localhost" as seen by the application server.

Source
Refer the source code for the ejbNodeDetails example present in <examples/ejbclient/ejbNodeDetails.java> for more information.

AdventNet, Inc.

295

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

Leaf Node Details


This is a sample application illustrating how to use the MibOperationsEJB to load MIBs and get the corresponding leaf node details for the LeafNode specified by the user. The following commands runs the application. ejbLeafDetails -m mibs\RFC1213-MIB 1.1 The above command loads the RFC 1213 MIB and retrieves the nodes details of sysDesc and prints them. For example, this example prints the following details. VALUE | DATA-TYPE To run the ejbLeafDetails application from another host where the application server runs, you can use the following command. java ejbLeafDetails - EJBServer SERVER -m mibs\RFC1213-MIB 1.1 It is assumed that the application server runs on a machine SERVER and you want to get the node details on the server itself. The argument "localhost" below specifies that ejbLeafDetails operation is performed on the "localhost" as seen by the application server.

Source
Refer the source code for the ejbLeafDetails example present in <examples/ejbclient/ejbLeafDetails.java> for more information.

AdventNet, Inc.

296

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

JFC MIB Tree


The example mibTreeDemo displays the usage of the MibTree bean with the JFC tree component. This example enables the loading and the using of SNMP MIBs. The following command can be used to run the application. java mibTreeDemo -m ../../mibs/RFC1213-MIB The above command loads the RFC1213-MIB in the MibTree component. We can traverse the MIB tree, read the MIB file description, and so on. The screenshot of this example is given below.

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

Other Examples
Request Server Demo RMI Request Server Demo SNMP Poller Demo RMI Applet Demo Property Settings Demo Line Graph Demo

This section discusses the various applet examples.

AdventNet, Inc.

298

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

Request Server Demo


This is a simple applet example to show the usage of the SnmpRequestServer bean. The RequestServerDemo example is used to get asynchronous requests. 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 requestServerDemo.html The screenshot of this applet example is given below.

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

RMI Request Server Demo


This is a simple applet example to show the usage of the rmiRequestServerDemo example. This example uses the SnmpRequestServer interface to get asynchronous requests. 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 rmiRequestServerDemo.html where '<JDK_HOME>' is the installation directory of JDK. The screenshot of this applet example is given below.

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

Source
Refer the source code for the rmiRequestServerDemo example present in <examples/rmiclient/rmiRequestServerDemo.java> for more information.

AdventNet, Inc.

301

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

RMI Applet Demo


This is a simple applet example to show the usage of the rmiAppletDemo example. This example uses the SnmpPoller interface for 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 rmiAppletDemo.html where, '<JDK_HOME>' is the installation directory of JDK. 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 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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

Property Settings Demo


This is a simple applet example to show the usage of the Property Settings bean along with the SnmpRequestServer bean. The settingsDemo example is used for setting properties of other beans during runtime. For example, the properties of the SnmpRequestServer bean, such as hostname, port number, etc. can be changed during runtime overriding the values set in the design time. 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 settingsDemo.html The screenshot of this applet example is given below.

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

Line Graph Demo


The example lineGraphDemo demonstrates the use of the LineGraph bean with the SnmpPoller bean. This example application enables to poll one or more OIDs and displays the values in a graphical format. Loading of MIBs, polling multiple OIDs, starting and stopping polling, etc. can be done. The following command can be used to run the application. java lineGraphDemo The screenshot of this example is given below.

Source
Refer the source code for the lineGraphDemo example present in <examples/uiapplications/lineGraphDemo.java> for more information.

AdventNet, Inc.

308

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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 SNMPAPI 4 SNMPv2c :: Help Documentation

Beans API Tutorial


In this section we will walk through the steps involved in developing simple applications using the high-level beans components (beans and ui packages). We will explain the steps involved in developing a simple application which is used for doing the basic SNMP GET operation. We will make a GET request for a single variable in a host in which the agent is running. The high-level beans components both non-ui (beans package) and GUI (ui package) components allows building more flexible applications and applets. The components can be used in any Java bean builder or directly in the Java code, using the API. The Beans components are built using the functions provided by the com.adventnet.snmp.snmp2 and com.adventnet.snmp.mibs packages. We will start by defining the class and the static main function required for the Java applications. We need to import the com.adventnet.snmp.beans package. The following example which uses the SnmpTarget bean shows the ease of use of the beans components in developing an application or applet. We need to instantiate the SnmpTarget bean, set the target host, specify the OID and perform SNMP operations. SnmpTarget target = new SnmpTarget(); target.setTargetHost("localhost"); target.setObjectID(".1.3.6.1.2.1.1.1.0"); System.out.println(target.snmpGet()); Now we can compile the program and see the result. Make sure that you provided the correct host name in the setTargetHost(). Refer the Java source for more information. This is a deliberately simple program, which is basically used to show the power and the easy way of using the Java Beans components. In case of applets we need to import the java.applet package along with the other AdventNet and JDK packages. Also we need to pass the applet constructor for the beans components we will be using. SnmpTarget target = new SnmpTarget(this); The rest of the steps will be the same.

AdventNet, Inc.

311

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

Low-Level API Tutorial


We will explain the steps involved in developing a simple application using the low-level API (com.adventnet.snmp.snmp2 package). We will make a GET request for a single variable in a host in which the agent runs. The com.adventnet.snmp.snmp2 package, which forms the low-level API, implements the core functions of the protocol. The com.adventnet.snmp.snmp2 package is the foundation on which the other APIs and services offered are built. We need to import the com.adventnet.snmp.snmp2 package in addition to the JDK packages as follows. import import import import java.lang.*; java.util.*; java.net.*; com.adventnet.snmp.snmp2.*;

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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 SNMPAPI 4 SNMPv2c :: Help Documentation

MIBs API Tutorial


Note: Go through the Tutorial on Low-Level API which details on the usage of com.adventnet.snmp.snmp2 package. We will explain the steps involved in developing a simple application using com.adventnet.snmp.mibs package. We will make a GET request for a single variable in a host in which the agent runs. The com.adventnet.snmp.mibs package provides MIB support for the API. This package is designed to allow Java programs to take full advantage of the information contained in the MIB module files. The mibs package facilitates loading and unloading of MIBs in applications and applets in addition to providing a host of functions that provide managed object properties. We will define the class and the static main function required for the Java applications. We need to import the com.adventnet.snmp.snmp2 and com.adventnet.snmp.mibs packages. We will set the host name as explained in Low-Level API Tutorial and load the MIB files. To load MIBs, we need to use the MibOperations class in the com.adventnet.snmp.mibs package. We use loadMibModules() to load the MIB file. MibOperations mibOps = new MibOperations(); try { mibOps.loadMibModules("RFC 1213-MIB"); } catch (Exception ex) {/p> } We set the OID for which we need to query by instantiating the SnmpOID class and using the MibOperations instance. SnmpOID oid = mibOps.getSnmpOID(".1.3.6.1.2.1.1.1.0"); The OID can also be set in the string format, such as "iso.org.dod ........." Use the SnmpPDU class for communication as explained in the Low-Level API Tutorial and get the response. We use any one of the following to print the descriptive value of the OID and the variables. This example, Mibsexample1, uses SnmpPDU for communication. System.out.println(mibOps.varBindsToString(pdu)); System.out.println(mibOps.toString(pdu)); System.out.println(pdu.printVarBinds()); The example, Mibsexample2, uses the SnmpSession class for communication instead of SnmpPDU. In this case, we use any one of the following to print the responses. System.out.println(mibOps.toString(var, oid)); System.out.println(oid.toTagString()); System.out.println(var.toTagString()); Now, we can compile the program and view the result. Ensure that you provided the correct host name in the setPeername(). Refer the source code for Mibsexample2 present in <tutorials/mibs_api/Mibsexample2.java> for more information.

AdventNet, Inc.

314

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

SAS API Tutorial


Note: Go through the Low-Level API Tutorial which details on the usage of com.adventnet.snmp.snmp2 package. We will explain the steps involved in developing a simple applet for SNMP management. We will make a GET request for a single variable in a host in which the agent is running. Web browsers place security restrictions on the applets in the communication of the devices in the network. Applets cannot directly communicate with any host on the network except the web server from which the applet was downloaded. The sas package provides support for the Java applets to get away with the security restriction of the browsers. SAS allows the applet to send and receive SNMP packets to any managed device from the applet host. SAS needs to be run with the web server in which the applet resides. For more information on running SAS, refer Installation and Setup. We will define the class required for the Java applets. We need to import the com.adventnet.snmp.snmp2 package. We need to instantiate and start the SNMP API as detailed in the Low-Level API Tutorial. The SASClient class in the com.adventnet.snmp.snmp2 package needs to be used for the SNMP communication. The SASClient class enables the applets to talk transparently to the SNMP devices through SAS. Applets do not have to instantiate this class explicitly. When SnmpSession is opened, it instantiates the SASClient class for communicating with SAS. The open(Applet) method instantiates the SASClient class. try { session.open(this); //open session for use by the applet } catch (SnmpException e ) { System.err.println("Error opening socket: "+e); } The SASClient constructor reads the SASPort.html file from the applet html directory to get the port on which SAS is available. The SASPort.html is created when SAS is started. A TCP connection is established between the applet and SAServer for the communication. The remaining steps are the same as discussed in the Low Level API Tutorial. Now, we can compile the program Sasexample. Ensure that you provide the correct host name in the setPeername(). Refer the source code for Sasexample present in <tutorials/sas_api/Sasexample.java> for more information. Now, create a HTML file, Sasexample, through which we can load the applet. Copy the HTML file and the class file to the Webserver directory (or any directory). Ensure that SAS is running and load the applet.

AdventNet, Inc.

315

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

Data Retrieval Tutorials


SNMP GET, GETNEXT Using High-Level API SNMP GET, GETNEXT (UI) Using High-Level API SNMP GET, GETNEXT Using Low-Level API SNMP GET, GETNEXT for Applets SNMP GET Using SAS Transport Framework SNMP GET Using TCP Polling with SnmpPoller

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 SNMPAPI 4 SNMPv2c :: Help Documentation

GET, GETNEXT Using High-Level API


We will explain the steps involved in developing a simple application for performing SNMP GET and GETNEXT operation. The high-level API consists of bean components that make the development of applications and applet much easier. 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. 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. public class SnmpGet { 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 hostname OID" ); System.exit(0); } String remoteHost=args[0]; We use the SnmpTarget bean for our SNMP operations. The SnmpTarget bean of the high-level API provides most of the SNMP operations and MIB-related functions and is used predominantly in our examples. The bean can be used as a class, directly in an application, an applet, or a combination of beans. We need to instantiate the SnmpTarget bean. SnmpTarget target = new SnmpTarget(); In case of applets, we need to import the java.applet package along with the other AdventNet and JDK packages. Also, we need to pass the applet constructor for the bean components. SnmpTarget target = new SnmpTarget(this); The SnmpTarget bean supports multiple variable requests. For a single variable request, we can use target.setObjectId() or target.setSnmpOID(). For multiple variable requests, we can use target.setObjectIDList() or target.setSnmpOIDList(). In this example, we get the hostname and the OID from the command line. target.setTargetHost(remoteHost); String oids[] = new String [args.length - 1]; for (int i=1; i < args.length; i++) oids[i-1]=args[i]; target.setObjectIDList(oids);

AdventNet, Inc.

317

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

SNMP GET, GETNEXT (UI) Using High-Level API


We will explain the steps involved in developing a simple UI application for performing the SNMP GET and GETNEXT operation. This simple application has a text field in which the user can enter the OID to be queried and another text field to display the results. The following beans components from the AdventNet SNMP API are used to develop this application. SnmpTarget (beans package) performs SNMP operations. Property Settings Bean (ui package) sets properties of beans during run time. For example, the properties such as host name and port number of the SnmpTarget bean can be changed during runtime, overriding the values set in the design time.

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

Note: In this tutorial example, you have to perform a GET first and then GETNEXT.

The screenshot of this tutorial example program is as follows.

Refer the source code for SnmpGetUI present in <tutorials/beans_ui_api/SnmpGetUI.java> for more information.

AdventNet, Inc.

322

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

SNMP GET, GETNEXT Using Low-Level API


We will explain the steps involved in developing a simple application for performing the SNMP GET and GETNEXT operation. This is similar to the Low-level API Tutorial provided in the Overview section. The SNMP GET operation retrieves one or more values from the managed agent's MIB. The GETNEXT operation does the same for the next object in the tree of objects on 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. In the example provided in the Overview section, we have given the hostname and the OID in the GET operation. We now modify this example to receive the hostname and the OID as command line inputs. We need to import the com.adventnet.snmp.snmp2 package in addition to the JDK packages listed. import import import import java.lang.*; java.util.*; java.net.*; com.adventnet.snmp.snmp2.*;

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

//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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

{ 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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

SNMP GET, GETNEXT for Applets


We will explain the steps involved in developing a simple applet for performing the SNMP GET and GETNEXT operation. This simple applet has a text field in which the user can enter the OID to be queried and another text field to display the results. Buttons are provided to perform GET and GETNEXT queries and to clear the text field. The UI of the applet is similar to the tutorial application explained in the GET, GETNEXT (UI) of the High-Level API Tutorials section. Here we discuss the changes we need to make for the applet. We need to import the java.applet package along with the other AdventNet and JDK packages. import import import import import java.applet.*; javax.swing.*; java.awt.event.*; com.adventnet.snmp.beans.*; com.adventnet.snmp.ui.*;

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

Loading the applet by using the applet viewer


The HTML file should have the following line within the "applet" tags. applet CODE = SnmpGetApplet.class We need to create a jar file which contains the example we have created and copy the jar file to the AdventNet classes directory. For example, create a jar file by name example.jar which contains the SnmpGetApplet.class. Ensure that the web server and SAS are started and load the HTML file as follows. http://localhost:8282/ If the applets contain any JFC/Swing components, we need to include a few more additional lines in the HTML file so that the web browsers invoke the proper plug-in and load the applet properly. Moreover, we need to ensure that it runs both in IE and Netscape. Refer the source code of the HTML file 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 The screenshot of this tutorial example program is as follows.

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 SNMPAPI 4 SNMPv2c :: Help Documentation

SNMP GET Using SAS Transport Framework


The SAS API, apart from the default protocols, also makes use of the transport provider framework for SAS communication, where the users can plug-in their own transport protocol between the SAS Client and the SAS server. Refer the SAS Transport Framework chapter for more information. In this tutorial, we explain the steps involved in developing a simple applet to perform the SNMP GET operation. This applet is similar to GET, GETNEXT, the only difference being transport communication used by SAS. The independent transport provider is implemented by using the interfaces SessionTransportProvider and TransportProvider in the com/adventnet/management/transport package. Both server side and client side implementation are provided and the transport communication should be registered with the SAS server. Once the client side implementation and the registration is complete the applet can make use of the registered transport provider by including the class file name of the implementation in the applet's HTML file. For example, if the client side implementation of the TransportProvider is com.adventnet.management.transport.TcpClientTransportImpl.java, the applet HTML file would contain the additional following line. PARAM NAME="TRANSPORT_PROVIDER" VALUE="com.adventnet.management.transport.TcpClientTransportImpl" Refer the source code of the applet and the HTML file for more information.

AdventNet, Inc.

328

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

SNMP GET Using TCP


We will explain the steps involved in developing a simple application for performing the SNMP GET using TCP as the transport communication. By default, SNMP uses UDP protocol for communication. AdventNet SNMP API provides an SNMP Transport Provider Framework by which the users can plug-in their own transport protocols. The API implements UDP/IP as the default protocol implementation. TCP/IP is provided as the reference implementation that uses the transport provider framework. This reference implementation is used as to explain how the users can plug-in their own transport protocol. This is similar to the example GET, GETNEXT, the only difference being the protocol used for communication. The SNMP GET operation retrieves one or more values from the managed agent's MIB. The mandatory values we need to provide are the host name in which the agent resides and the OID that needs to be queried. We need to make sure that the agent accepts the TCP packets for communication. We need to import the com.adventnet.snmp.snmp2 package in addition to the JDK packages listed. import import import import java.lang.*; java.util.*; java.net.*; com.adventnet.snmp.snmp2.*;

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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 SNMPAPI 4 SNMPv2c :: Help Documentation

Polling with SnmpPoller


We will explain the steps involved in developing a simple application for doing automatic polling of variables from remote agent. We use the SnmpPoller bean to develop our application. This example application retrieves the value of the given variable at a specified interval of time. 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 implement the ResultListener interface, which responds to the SNMP requests. public class SnmpPolling implements ResultListener { public static void main(String args[]) { We get the hostname and the OID as the command line inputs. if( args.length < 2) { System.out.println("Usage : java SnmpPolling hostname OID"); System.exit(0); } String remoteHost="args[0]"; String OID = "args[1]"; We use the SnmpPoller bean for polling the MIB variables. Instantiate the SnmpPoller bean and set the host name and the OID. We set the polling interval as one second. The application polls the agent every second and get the value. SnmpPoller poller = new SnmpPoller(); poller.setTargetHost(remoteHost); poller.setObjectID(OID); poller.setPollInterval(1); Now, we register the ResultListener interface with the poller component. poller.addResultListener(this); The ResultListener interface contains the following methods: setResult(), setNumericResult(), and setStringResult(). We implement the setResult() to get the result. public void setNumericResult(long l) { } public void setResult(ResultEvent result) { try{ System.out.println(result.getStringValue()); } catch (DataException de) { System.out.println("Error in getting agent data: "+de + result.getErrorString()); } }

AdventNet, Inc.

332

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

Data Altering Tutorials


SNMP SET Using High-Level API SNMP SET (UI) Using High-Level API SNMP SET Using Low-Level API

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 SNMPAPI 4 SNMPv2c :: Help Documentation

SNMP SET Using High-Level API


We will explain the steps involved in developing a simple application for performing the SNMP SET operation. 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. 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. public class SnmpSet { public static void main(String args[]) { We get the hostname, OID, the MIB file name, and the value as the command-line inputs. if( args.length < 4) { System.out.println("Usage :java SnmpSet hostname OID mibs value"); System.exit(0); } String remoteHost="args[0]"; String OID = args[1]; String mibs = args[2]; String value = args[3]; We use the SnmpTarget bean for our SNMP operations. The SnmpTarget bean of the high-level API provides most of the SNMP operations and MIB-related functions and is used predominantly in our examples. Instantiate the SnmpTarget bean and set the host name and the OID. SnmpTarget target = new SnmpTarget(); target.setTargetHost(remoteHost); target.setObjectID(OID); We load the MIB file to find the type of the object used in SET operation. try { target.loadMibs(mibs); } catch (Exception ex) { System.err.println("Error loading MIBs: "+ex); } Now, we perform the SNMP SET operation and print the results. try { String result = target.snmpSet(value); // does the SNMP SET operation. System.out.println("Response PDU received from " +target.getTargetHost() + ", community: " +

AdventNet, Inc.

335

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

SNMP SET (UI) Using High-Level API


Note: Go through the Tutorial example on GET, GETNEXT (UI) that explains the development of a simple UI application We will explain the steps involved in developing a simple UI application for performing the SNMP SET operation. The SET operation allows the management application or the manager to set the value of an attribute of a managed object in the agent. The application has a text field in which the value to be set can be entered, MibTree to load the MIBs, and few other UI components. Refer MibTree Tutorial to know more about the MibTree component. The following bean components are used to develop this application. SnmpTarget MibTree Property Settings JButton JTextArea JTextField JFrame 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 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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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 SNMPAPI 4 SNMPv2c :: Help Documentation

SNMP SET Using Low-Level API


We will explain the steps involved in developing a simple application for performing the SNMP SET operation. The SET operation 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, we need to provide the host name in which the agent resides, OID, the type, and the value for the managed object. We get the host name, OID, type, and value as command line inputs. if(args.length < 4) { System.out.println("Usage: java snmpset hostname OID type value"); System.exit(0); } String remoteHost="args[0]"; String OID = "args[1]"; String type = "args[2]"; String value = "args[3]"; We need to instantiate and start the SnmpAPI and open SnmpSession. Then, we instantiate SnmpPDU and use setCommand() to send an SNMP SET request. The command constants are defined in the SnmpAPI class. SnmpPDU pdu = new SnmpPDU(); >pdu.setCommand(SnmpAPI.SET_REQ_MSG ); To perform the SET operation, we need to build the variable binding or the varbinds. The variable binding or the varbind is the pairing of the OID and its corresponding value. Therefore, we need to know the OID, the type of the OID, and its value to build the varbind. Instantiate the SnmpOID class and the get the OID from the command line. SnmpOID oid = new SnmpOID(OID); //taken from the command line The type of the variable can be INTEGER, STRING, COUNTER, etc. The SnmpAPI class provides constants for all the SNMP data types. Therefore, we check the validity of the data type. In this example, we check only for the type STRING. The code should include all the known SNMP data types. byte dataType; if (type.equals("STRING")) { //type taken from the command-line dataType = SnmpAPI.STRING; } else { System.err.println("Invalid variable type: " + type); return; } The createVariable() method available in the SnmpVar class provides a means of creating any SNMP variable object with a given value. This method takes the type of SNMP data and the value and returns an SnmpVar object. The type argument can take any value as defined in the SnmpAPI class.

AdventNet, Inc.

340

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

Receive Trap Using High-Level API


We will explain the steps involved in developing a simple application to receive the trap messages sent by agent. Traps are unsolicited messages sent by an agent to the management stations to report the conditions of the managed node. The high level API provides the SnmpTrapReceiver bean for receiving traps. The trap receiver bean listens and receives the traps sent from the agents. The trap receiver bean generates an event when an SNMP trap is received. The trap event that contains the trap data is forwarded to the registered trap listener objects. The trap listener then handles the received trap. The high-level API provides the following classes. SNMP Trap Receiver - receives traps and generates trap event as per the JDK 1.1 event model. Trap Event - event generated by the trap receiver bean. Trap Listener - listener for traps.

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

Send Trap Using High-Level API


We will explain the steps involved in developing a simple application to send an SNMPV1 trap message. Trap messages are unsolicited messages sent by an agent to the management stations to report the conditions of the managed node. To send the v1 trap message we need to provide the following values. remoteHost - the manager station to which the trap message is sent. enterprise - the enterprise OID (sysObjectID for generic traps). agent-addr - the agent address from which the trap is generated. generic trap - the code for generic trap type. specific-trap - the code for specific trap type. timeticks - the time elapsed between the last initialization of the network and the generation of the trap. MIB file, OID, and value - values for building the varbinds.

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

Receive Trap (UI) Using High-Level API


Note: Go through the Tutorial examples on GET, GET NEXT (UI) that explains the development of a simple UI application. We will explain the steps involved in developing a simple UI application for receiving SNMP traps. Traps are unsolicited messages sent by an agent to the management stations to report the conditions of the managed node. This application simply waits at a specified port (8001 in our example) and displays the trap information it receives. This is similar to the Receive Trap Tutorial. We use the SnmpTrapReceiver bean and the TrapListener interface to handle the traps. The following bean components are used to develop this application. SnmpTrapReceiver JButton JTextArea JFrame

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

Send and Receive Trap (UI) Using High-Level API


Note: Go through the Tutorial examples on GET, GETNEXT (UI) that explain the development of a simple UI application. This example builds on the Receive Trap (UI) to receive traps. For tutorial purposes, we have included a "Send Trap" button, which sends a trap to the specified port (8001 in our example). The trap sent is received in the application and the trap information is displayed. The following beans components are used to develop this application. SnmpTarget SnmpTrapReceiver JButton JTextArea JFrame

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

The screenshot of this tutorial example program is as follows.

Refer the source code for SnmpSendTrapUI present in <tutorials/beans_ui_api/SnmpSendTrapUI.java> for more information.

AdventNet, Inc.

351

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

Receive Trap (UI) Using TrapBrowser


Note: Go through the Tutorial examples on GET, GET NEXT (UI) that explain the development of a simple UI application. This example uses two additional beans components namely TrapBrowser and TrapParser for receiving traps. TrapBrowser is used to display trap details and TrapParser is used to parse the trap events. The SnmpTrapReceiver bean receives the traps from the agents and generates the trap events. The TrapParser bean gets trap event from the SnmpTrapReceiver and parses the trap event. The TrapBrowser displays the parsed trap events. For tutorial purposes, we have included a "Send Trap" button which sends a trap on the specified port (8001 in our example). The following bean components are used to develop this application. SnmpTarget SnmpTrapReceiver TrapBrowser TrapParserBean JButton JFrame

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

The screenshot of this tutorial example program is as follows.

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 SNMPAPI 4 SNMPv2c :: Help Documentation

Receive Trap Using Low-Level API


We will explain the steps involved in developing a simple application to receive the trap messages sent by agent. Traps are unsolicited message sent by the agent to the management stations to report the conditions of the managed node. There are two ways by which an application can receive an SNMP trap message. Using callback() method in the interface SnmpClient. Using receive() in SnmpSession

Using callback() in SnmpClient


The interface SnmpClient is used by applications to send and receive messages asynchronously. The SnmpClient interface implements callback, authentication, and debugging functions. We implement SnmpClient in our main class. public class SnmpTrapd implements SnmpClient { We need to instantiate and start the SnmpAPI and open SnmpSession. We need to add the SnmpClient interface implementation to the session to invoke the callback, authentication, and debugging functions. session.addSnmpClient(new SnmpTrapd()); By convention, the traps are received at the port 162. In this example, we set the local port to 8001 for receiving the traps. // set local port SnmpPDU pdu = new SnmpPDU(); UDPProtocolOptions option = new UDPProtocolOptions("localhost"); pdu.setProtocolOptions(option); pdu.setLocalPort(8001); System.out.println("Waiting to receive traps in the port "+session.getLocalPort() +"......."); Now, we have to implement three methods of the SnmpClient interface. 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) { 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() +",

AdventNet, Inc.

355

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

Using receive() in SnmpSession


We need to instantiate and start SnmpAPI and open SnmpSession. We set the community and the local port in which the trap can be received. We need to instantiate the SnmpPDU and use session.receive() to wait for a PDU that is not null. If the pdu.command is equal to TRAP_REQ_MSG, an SNMP trap message is received. // wait for the trap pdu SnmpPDU pdu = new SnmpPDU(); pdu = session.receive(0); System.out.println("Waiting to receive traps in the port "+ session.getLocalPort() +"......."); while (pdu == null) { pdu = session.receive(0); if(pdu != null) { if (pdu.getCommand() == SnmpAPI.TRP_REQ_MSG) { // print the received trap information 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()); pdu = null; System.out.println("Continues waiting to receive traps in the port "+option.getLocalPort() +"......."); } else System.err.println("Non trap PDU received."); }

AdventNet, Inc.

356

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

Send Trap Using Low-Level API


We will explain the steps involved in developing a simple application to send an SNMPv1 trap message. Trap messages are unsolicited message sent by the agent to the management stations to report the conditions of the managed node. To send the v1 trap message, we need to provide the following values. remoteHost - the manager station to which the trap message is sent. enterprise - the enterprise OID (sysObjectID for generic traps). agent-addr - the agent address from which the trap is generated. generic trap - the code for generic trap type. specific-trap - the code for specific trap type. timeticks - the time elapsed between the last initialization of the network and the generation of the trap. OID, type, and value - values for building the varbinds.

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

Tutorial Command line example for sending SNMPv1 trap Command line example for sending SNMPv2c trap Command line example for sending SNMPv3 trap

Available In <examples/low_level_api_examples/snmpapps/snmpv1trap.java> <example/low_level_api_examples/snmpapps/snmpv2ctrap.java> <examples/low_level_api_examples/snmpapps/snmpv3trap.java>

AdventNet, Inc.

360

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

Receive Traps for Applets


We will explain the steps involved in developing a simple applet to receive the trap messages sent by agent. Traps are unsolicited messages sent by agent to management stations to report the conditions of the managed node. Applets receiving traps should register with SAS. SAS listens for the traps in the specified port and forwards it to the applets. Refer Receive Trap in the Low-Level API Tutorials section which is a simple example application for receiving traps. Here we discuss the changes we need to make for the applet. Import the following packages. import import import import java.applet.*; java.io.*; javax.swing.*; com.adventnet.snmp.snmp2.*;

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

The screenshot of this tutorial example program is as follows.

Refer the source code for viewTrap present in <tutorials/sas_api/viewTrap.java> for more information.

AdventNet, Inc.

363

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

Table Handling Tutorials


Retrieve Table with TableBean Retrieve Table with SnmpTable Retrieve Table with SnmpAugmentTable Retrieve Table with SnmpTableModel Retrieve Table with SnmpTablePanel Retrieve Table with SnmpTarget

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

Retrieve Table with TableBean


Note: Go through the Tutorial example on GET, GET NEXT (UI), which explains the development of a simple UI application. We will develop a simple UI application using TableBean component for displaying the table information. The TableBean component is an implementation of the combination of JTable and SnmpTableModel components. The following bean components will be used in this example. TableBean JFrame JScrollPanel

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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 TableBean Available In <tutorials/beans_ui_api/SnmpGetTableUI_one.java> <examples/uiapplications/tableBeanDemo.java>

AdventNet, Inc.

366

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

Retrieve Table with SnmpTable


We will explain the steps involved in developing a simple application for retrieving the SNMP Tables from a remote agent using the SnmpTable bean. This is a simpler way of getting table information. 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. public class SnmpGetTable_one { public static void main(String args[]) { We get the hostname and the table OID as the command line inputs. if(args.length < 2) { System.out.println("Usage : java SnmpGetTable_one hostname tableoid"); System.exit(0); } String remoteHost="args[0]"; String tableoid = "args[1]"; We use the SnmpTable bean to retrieve the table. We instantiate the SnmpTable bean and set the host name. SnmpTable table = new SnmpTable(); target.setTargetHost(remoteHost); We load the MIB file and set the table OID. try{ table.loadMibs("RFC1213-MIB"); table.setTableOID(tableoid); } catch (Exception ex) { System.err.println("Error loading MIBs: "+ex); } Now, we can print the table. The SnmpTable class provides several useful methods which make the table retrieval much easier. The getColumnCount() and the getRowCount() are used to find the number of columns and the rows in the table. The getColumnName() gives the name of the column of the table. The getValueAt() is used to return the value of a particular cell of the table. System.out.println("Getting table. Table items:"); StringBuffer sb = new StringBuffer(); try { Thread.sleep(10000); } // allow some time to get all rows catch (InterruptedException ex) {

AdventNet, Inc.

367

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

} 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 SNMPAPI 4 SNMPv2c :: Help Documentation

Retrieve Table with SnmpAugmentTable


We will explain the steps involved in developing a simple application for retrieving the SNMP Augment Table from a remote agent using the SnmpAugmentTable bean. This is a simpler way of getting table information. 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. public class GetSnmpAugmentTable { public static void main(String args[]) { We get the hostname and the table OID as the command line inputs. if(args.length < 2) { System.out.println("Usage : java GetSnmpAugmentTable hostname tableoid"); System.exit(0); } String remoteHost="args[0]"; String tableoid = "args[1]"; We use the SnmpAugmnetTable bean to retrieve the table. We instantiate the SnmpAugmentTable bean and set the host name. SnmpAugmentTable table = new SnmpAugmentTable(); target.setTargetHost(remoteHost); We load the MIB file and set the table OID. try{ table.loadMibs("IF-MIB"); table.setTableObjectID(tableoid); } catch (Exception ex) { System.err.println("Error loading MIBs: "+ex); } The table values can be obtained as shown below. System.out.println("Getting table. Table items:"); StringBuffer sb = new StringBuffer(); try { Thread.sleep(10000); } // allow some time to get all rows catch (InterruptedException ex) { }

AdventNet, Inc.

369

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

Retrieve Table with SnmpTableModel


Note: Go through the Tutorial examples on GET, GETNEXT (UI) that explain the development of a simple UI application. The AdventNet API provides the following three UI bean components for retrieving and displaying the SNMP table information in UI applications. SnmpTableModel TableBean SnmpTablePanel

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

Retrieve Table with SnmpTablePanel


Note: Go through the Tutorial examples on GET, GETNEXT (UI) that explain the development of a simple UI application. In this tutorial example, we will develop a simple UI application using SnmpTablePanel component for displaying the table information. SnmpTablePanel is typically used for displaying large tables and it has several features, such as adding rows, graph, etc. The following bean components are used in this example. SnmpTablePanel JFrame

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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 SNMPTablePanel Comprehensive example on using SNMPTablePanel Available In <tutorials/beans_ui_api/SnmpGetLargeTable.java> <examples/uiapplications/largetable.java>

AdventNet, Inc.

374

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

Retrieve Table with SnmpTarget


We will explain the steps involved in developing a simple application for retrieving SNMP tables from a remote agent. We use the SnmpTarget bean to develop our application and some classes from the mibs and snmp2 package. We need to import the com.adventnet.snmp.beans,mibs,and snmp2 packages along with the JDK packages. import import import import com.adventnet.snmp.beans.*; com.adventnet.snmp.mibs.*; com.adventnet.snmp.snmp2.*; java.util.*;

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

MIB Handling Tutorials


Traverse MIB (UI) with MibTree Browse MIB (UI) with MibBrowser Retrieve Mib Node Information with MIB API

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

Traverse MIB (UI) with MibTree


Note: Go through the Tutorial examples on GET, GET NEXT (UI) that explain the development of a simple UI application. We will explain the steps involved in developing a simple UI application through which we can load and unload the MIBs, traverse the MIB Tree, read the MIB file description, and so on. The MibTree component of the com.adventnet.snmp.ui package is used for this. The following bean components are used to develop this application. MibTree JButton JTextArea JFrame

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

The screenshot of this tutorial example program is as follows.

Refer the source code for SnmpMibTree present in <tutorials/beans_ui_api/SnmpMibTree.java> for more information.

AdventNet, Inc.

380

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

Browse MIB (UI) with MibBrowser


In this example, we have included the MibBrowser bean, which is a part of the com.adventnet.snmp.ui package. The MibBrowser bean is a complete SNMP MibBrowser that can be integrated into your management applications and be used to provide the MIB browsing and other related functions. The screenshot of this tutorial example program is as follows.

Refer the source code for SnmpMibBrowser present in <tutorials/beans_ui_api/SnmpMibBrowser.java> for more information.

AdventNet, Inc.

381

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

Retrieve MIB Node Information with MIBs API


We will explain the steps involved in developing simple application that can be used to retrieve the node information from the MIB files. The MibNode and the LeafSyntax class provide the methods necessary to access information available about the nodes in the MIB file. In this example, we also explain the usage of the MibNode class in retrieving the node information. Import the com.adventnet.snmp.snmp2 package and the com.adventnet.snmp.mibs package. import com.adventnet.snmp.snmp2.*; import com.adventnet.snmp.mibs.*; Define the required class and the static main function. public class MibNodeInfo { public static void main(String args[]) { Get the OID and the MIB file as the command line inputs. if( args.length < 2) { System.out.println("Usage : java MibNodeInfo mibfile OID"); System.exit(0); } String mibfile = args[0]; String OID = args[1]; 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. MibOperations mibops = new MibOperations(); try { mibops.loadMibModules(mibfile); } catch (Exception ex) { System.err.println("Error loading MIBs: "+ex); } Instantiate the SnmpOID class to get the OID for which we need the information by using getSnmpOID() of the MibOperations class. SnmpOID oid = mibops.getSnmpOID(OID); Instantiate the MibNode class and use getMibNode() in the MibOperations class to get the MibNode. MibNode node = mibops.getMibNode(oid); MibNode, say for the OID sysDescr in RFC1213-MIB, can also be got directly as follows. MibNode node = mibops.getMibNode("sysDescr");

AdventNet, Inc.

382

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

Graphs with LineGraphBean


Note: Go through the Tutorial example on GET, GET NEXT (UI) that explain the development of a simple UI application. AdventNet API provides two Graph beans namely LineGraphBean and BarGraphBean for plotting the values polled from one or more variables from the remote agent. The SnmpPoller component is used for polling the agent. The SnmpPoller component polls the agent and generates ResultEvent events. The Graph bean components implement the ResultListener interface, which listens for these ResultEvent events. These result events contain the result data. The following bean components can be used to develop this application. SnmpPoller LineGraphBean PropertySettings JFrame

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

Address and Name Lookup


The Applet Support API provides support to resolve between internet host names and addresses. Applets can map IP address to host names and resolve host names to the IP addresses using the methods in the SASClient class. In this example, we develop an applet which performs the address and the name lookup. 1. Import the following packages. import import import import import java.applet.*; java.lang.*; java.awt.*; java.awt.event.*; com.adventnet.snmp.snmp2.*;

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

{ 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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

SAS as Part of an Application


SNMP Applet Server (SAS), which runs on a web server, allows the applet to send and receive SNMP packets to any managed device on the network. SAS provides communication for applets that are unable to connect directly to managed devices due to security limits. It uses a TCP socket connection to provide this function. SAS can be started as a standalone application by giving the following command. java com.adventnet.snmp.sas.SAServer SAS can also be integrated with other applications so that SASserver can be started as part of that application. 1. Import the following packages. import import import import import import javax.swing.*; java.awt.*; java.net.*; java.io.*; java.awt.event.*; com.adventnet.snmp.sas.*;

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

The screenshot of this tutorial example program is as follows.

Refer the source code for SASTestAppn present in <tutorials/sas_api/SASTestAppn.java> for more information.

AdventNet, Inc.

392

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

Performance Numbers for Modules


The following tests were performed on: Operating System - Linux Red Hat 7.2 (Enigma) RAM - 512 MB Processor - PIV 1.8 GHz JDK version - 1.5.0 Host for SNMP Request - localhost Database Used - MySql 4.0.17 OID Queried - 1.5.0 Number of requests sent - 10000

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

Note: All requests are SNMP GET requests.

AdventNet, Inc.

395

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

Performance Numbers for MIB Loading Options


The following tests were performed on: Operating System - Red Hat Linux 7.2 (Enigma) RAM - 512 MB Processor - PIV 1.8 GHz JDK version - 1.5.0 Database Used - Mysql

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

Performance Numbers for Traps


AdventNet's Trap Receiver can receive traps approximately 3100 traps/sec if there are no processing for traps received. If the incoming trap rate is greater than 3100, the TrapReceiver may start losing traps. The following tests were performed on: Operating System - Red Hat Linux 7.2 (Enigma) RAM - 512 MB Processor - PIV 1.8 GHz JDK version - 1.5.0 Module Low-Level API High-Level API Receiving Rate (Traps/second) 3100 3000

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

Migration from 3.x to 4.0


High-Level API Changes Low-Level API Changes MIBs API Changes

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

High-Level API Changes


The API changes in high level are listed below. S.No. 1 Deprecated Method/Variable getOverwriteCMI() Class Name SnmpServer Comment Instead use isOverwriteCMI() method. Instead use getModules() and getModuleNames() methods respectively.

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

S.No. Deprecated Method/Variable

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

set(SnmpOID oid, SnmpVar var)

18

set(String oidString, String setString, byte type)

AdventNet, Inc.

404

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

setSocketParms(int socketTimeout, int socketDelay) setStartLocalPort(int startLocalPort)

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

MIBs API Changes


The API changes in MibOperations are listed below. S.No. 1 2 Deprecated Method/Variable getThrowFileNotFound setThrowFileNotFound Comment The setThrowFileNotFound(boolean) method is deprecated and therefore FileNotFound exception thrown by loadMibModule(). It is mandatory that the imported modules should be present in the directory in which the MIB files are loaded.

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

Migration from 2.x to 4.0


Low-Level API Changes MIBs API Changes

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

Low-Level API Changes


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); 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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

S.No. Deprecated Method/Variable

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

set(SnmpOID oid, SnmpVar var)

18

set(String oidString, String setString, byte type)

AdventNet, Inc.

411

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

setSocketParms(int socketTimeout, int socketDelay) setStartLocalPort(int startLocalPort)

26

AdventNet, Inc.

412

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

MIBs API Changes


The API changes in MibOperations are listed below. S.No. 1 2 Deprecated Method/Variable getThrowFileNotFound setThrowFileNotFound Comment The setThrowFileNotFound(boolean) method is deprecated. It is mandatory that the imported modules should be present in the directory in which the MIB files are loaded.

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

FAQs
Beginners FAQs General Beans Components Low-Level API MIBs API SAS and Web Server EJB API RMI API CORBA API

This section contains FAQs related to various packages of the API.

AdventNet, Inc.

415

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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 SNMPAPI 4 SNMPv2c :: Help Documentation

FAQs - Bean Components


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? 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. 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? 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"? 5. How do I handle the timeout events separately while performing the SNMP operations? 6. How do I perform a GET operation in the loaded MIB by using the SnmpTarget bean? 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? 8. The trapreceiver Bean works fine in Windows but gives the java.net.BindException error in Unix. 9. When I load the AdventnetSnmp.jar in the Visual Cafe, some of the Beans have problem in loading. What should I do? 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? 11. How can I use the LineGraph Bean? 12. I use the SnmpTarget Bean. What is the difference between setCommunity() and setWriteCommunity()? 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? 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? 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? 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? 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? 18. When I get an SnmpOID, 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. 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?

AdventNet, Inc.

424

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

{ 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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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 SNMPAPI 4 SNMPv2c :: Help Documentation

FAQs - Low-Level API


1. Can SnmpSession automatically detect the version of the SNMP agent on the other end? 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? 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. 4. I would like to use your API in a multithreaded application to collect some data. Is AdventNet SNMP API multithread safe? 5. What is an OCTET in terms of bits? I am trying to determine a bandwidth tilization factor and I need to figure out how to represent an OCTET or a packet in bits. 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()? 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? 8. Can I perform a multiple OID query? If yes, how many OIDs can I query with a single SNMP GET? 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? 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? 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"? 12. When I receive a PDU from the SNMP agent, how can I differentiate between a normal String and HEX-answer? 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? 14. How do I set UDP port explicitly for sending GET/SET/GETNEXT request? 15. When I ask for 10 rows in an SNMP table, 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? 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? 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 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?

AdventNet, Inc.

431

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

FAQs - MIBs API


1. I need to generate and decode MIB table indexes. How do I use the methods decodeInstanceString(), encodeInstanceString(), getIndexes(), and getIndexes(MibOperations) for this purpose. How do I generate their parameters, and how do they relate to each other? Do these methods support augmented tables? Do these methods support IMPLIED indexes? 2. How do I know if a table is augmented (from the interface)? How do I get a reference to the conceptual index? 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? 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? 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? 6. How do I load the MIBs in my application? 7. How do I get the root OID and the labels of the variables? 8. Can SNMP API return me the string value that is defined in the MIB, when I receive the response? 1. I need to generate and decode MIB table indexes. How do I use the methods decodeInstanceString(), encodeInstanceString(), getIndexes(), and getIndexes(MibOperations) for this purpose. How do I generate their parameters, and how do they relate to each other? Do these methods support augmented tables? Do these methods support IMPLIED indexes? The two methods getIndexNames() and getIndexes() in MibNode is for getting the index name and node of the table. The getIndexNames() returns vector of indexes (as String) for the table when invoked on the entry node of the table while getIndexes() returns vector of indexes (as MibNode) when invoked on any of the column nodes of the table. The encodeInstanceString() encodes an instance string based on the indexVector (vector of basic SNMP type values). The instance int array should be concatenated to the OID int array to get the complete OID. For example, the tcpConnTable has the following entry. tcpConnState tcpConnLocalAddress tcpConnLocalPort tcpConnRemAddress tcpConnRemPort established(5) 128.253.154.64 23 128.253.154.3 1111

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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 SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

FAQs - SAS and Web Server


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/SnmpSession.op en}: cannot access 6001. What do I do? 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? 3. I want to load applet that I created through the applet viewer. What should I do? 4. I want to view the applet that I created in a web browser. What should I do? 5. How do I make my applet connect to SAS when it is loaded through the web server? 6. The SAS server runs in my web server host. Why does not my applet connect to SAS? 7. Why do I get an Applet Security exception when I load a MIB file in the example applet that I developed? 8. Why do I get a Security exception while locally loading a MIB file in the MibBrowser applet using Netscape? 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.

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

FAQs - EJB API


1. Is SnmpEJBServer an EJB container? What is SnmpEJBServer factory? How are they related? Where do they run? 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. 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? 1. Is SnmpEJBServer an EJB container? What is SnmpEJBServer factory? How are they related? Where do they run? The SnmpEJBServer is a remote interface and the SnmpEJBServerImpl is the corresponding implementation class that internally calls the SNMP rmi package classes. The SnmpEJBServer resides inside the EJB application server and outside the EJB container. The EJB 1.1 specification limits EJB from doing any of the following. Managing or synchronizing threads Accessing files or directories with the java.io package Using AWT functionality to display or accept information Listening on a socket, accepting connections on a socket, or using a socket for multicast Setting a socket factory (used by ServerSocket, Socket) or the stream handler factory (used by the URL class) Loading a native library.

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

FAQs - RMI API


1. RMI applications with JDK 1.2 throw SecurityException. How do I avoid this? 2. Our product currently uses the com.adventnet.snmp.rmi package, the SnmpTarget, 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? 3. RMI requests are slow in Windows NT and Windows 2000 machines. Why is this so? 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. 1. RMI applications with JDK 1.2 throw SecurityException. How do I avoid this? To run rmi in JDK1.2 environment, you need to set the security permission and file permission as follows. grant { // allows anyone to listen on un-privileged ports permission java.net.SocketPermission "localhost:161-65535", "listen,accept,connect,resolve"; // Assuming mibs directory is present in the c Drive. permission java.io.FilePermission "c:\\mibs\\-","read, write"; }; A sample SNMPRmi.policy file is available in the rmiclient sub directory in the examples directory. To run the AdventNetSNMP rmi server, give the following command from the rmiclient directory. java -Djava.security.policy=SNMPRmi.policy com.adventnet.snmp.rmi.SnmpFactoryImpl Alternatively, you can use the files start_rmi_server.bat (Windows) or start_rmi_server.sh (Linux/Solaris) present in rmiclient directory. Note: For granting file permissions to different directories, you may need to edit the SNMPRmi.policy and include the directory names in the policy file.

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

FAQs - CORBA API


1. I use the CORBA support of the AdventNet API and the target object of this class. If some errors occur during CORBA communication or the operation, there is an exception generated, such as "CORBA COMM Failure." or an org.omg.CORBA.SystemException. How can I report normal SNMP error messages, such as "No such name error"? 2. How do I use Visigenic Visibroker ORB with AdventNet CORBA API? 3. Which IDL compiler is used to make those ORBs? 4. What version of CORBA is supported/implemented by the AdventNet SNMP API? 1. I use the CORBA support of the AdventNet API and the target object of this class. If some errors occur during CORBA communication or the operation, there is an exception generated, such as "CORBA COMM Failure." or an org.omg.CORBA.SystemException. How can I report normal SNMP error messages, such as "No such name error"? To get the Snmp error message we can use one of the following. Exception Handling CallBack

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

AdventNet SNMPAPI 4 SNMPv2c :: Help Documentation

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

S-ar putea să vă placă și