asp tutorials, asp.net tutorials, sample code, and Microsoft news from 15Seconds
Data Access  |   Troubleshooting  |   Security  |   Performance  |   ADSI  |   Upload  |   Email  |   Control Building  |   Component Building  |   Forms  |   XML  |   Web Services  |   ASP.NET  |   .NET Features  |   .NET 2.0  |   App Development  |   App Architecture  |   IIS  |   Wireless
 
Pioneering Active Server
 Power Search








Active News
15 Seconds Weekly Newsletter
• Complete Coverage
• Site Updates
• Upcoming Features

More Free Newsletters
Reference
News
Articles
Archive
Writers
Code Samples
Components
Tools
FAQ
Feedback
Books
Links
DL Archives
Community
Messageboard
List Servers
Mailing List
WebHosts
Consultants
Tech Jobs
15 Seconds
Home
Site Map
Press
Legal
Privacy Policy
internet.commerce














internet.com
IT
Developer
Internet News
Small Business
Personal Technology
International

Search internet.com
Advertise
Corporate Info
Newsletters
Tech Jobs
E-mail Offers

HardwareCentral
Compare products, prices, and stores at Hardware Central!

Creating an SNMP Component
By Ben Garcia
Rating: 4.5 out of 5
Rate this article


  • email this article to a colleague
  • suggest an article

    Introduction

    In the world of network management, SNMP (Simple Network Management Protocol) stands as one of the most widely used protocols. It's very difficult to find a manageable device that does not come packaged with this functionality. As the needs of our community grow and technology evolves, we must be able to effectively ensure network and application integrity.

    This article has made the following assumptions:

    • The reader is familiar with the Visual C++ 6.0 environment
    • The reader has a good understanding of the Component Object Model

    The source code for this article shows how to communicate with SNMP v1.0 enabled devices.

    There have been two versions of SNMP released since version 1. Version 1, however, is still the most widely implemented version. SNMP v2 showed no visible change between v1 and v2 (no true gain). SNMP v3 was never implemented because it was too complex and didn't follow the original intent of SNMP -- simplicity.

    History of SNMP

    Synopsis

    The Simple Network Management Protocol grew from the necessity to manage TCP/IP based networks, as well as the Internet as a whole. The base model and conceptualization was created by:

    • Keith McCloghrie [The Wollongong Group, Inc.]
    • Marshal Rose [The Wollongong Group, Inc.]
    • Jeffrey D. Case [University of Tennessee]
    • Mark Fedor [NYSERNET]
    • Martin Lee Schoffstall [Rensselaer Polytechnic Institute]
    • James R. Davin [Proteon, Inc.]

    NOTE: Places listed above were accurate at time of publication for RFC 1052 and 1065

    In April of 1988, the IAB (Internet Architecture Board) released RFC 1052, "IAB Recommendations for the Development of Internet Network Management Standards." The purpose of this document was to define a set of standards for all network management protocols in a TCP/IP environment, as well as development within the network management arena. It states that SNMP is to be the foundation of network management in a short-term.

    In August of 1988, SNMP was first released in RFC 1067, which was accompanied by two other RFC's:

    • [RFC 1066] Structure and Identification of Management Information for TCP/IP-based internets
    • [RFC 1065] Management Information Base for Network Management of TCP-IP-based internets

    These documents provided the groundwork for SNMP that eventually lead to its version 1.0 release in May of 1991. The combination of the following documents represents the SNMP v1.0 implementation:

    • [RFC 1155] Structure and Identification of Management Information for TCP/IP-based internets
    • [RFC 1157] A Simple Network Management Protocol (SNMP)
    • [RFC 1212] Concise MIB Definitions
    • [RFC 1213] Management Information Base for Network Management of TCP/IP-based internets
    Stepping Stone

    The Simple Gateway Management Protocol (SGMP) was released in RFC 1028 on November 1987 by:

    • James R. Davin
    • Jeffrey D. Case
    • Mark Fedor
    • Martin Lee Schoffstall

    Its overall goal was to reduce the complexity of management functions within a gateway. With this objective in mind, it would allow developers of such software to easily adapt and implement these specifications. The architecture was designed to be platform independent allowing it the ability to safely interact with its host (i.e. router).

    SGMP was confined to only monitoring gateways, which did not provide the means to manage a diverse environment. It became the stepping-stone in the development of SNMP, which is why the architecture between the two protocols is very similar. SNMP was built to be environment independent - anything from desktop computers to network devices.

    SNMP Architecture

    Overview

    SNMP is formed around the Manager/Agent model and operates in layer five (or the Session layer) of the OSI model. Network management utilizing SNMP in a standard setting consists of:

    • 1 or more managers or management stations
      • Central point of both data collection and distribution
        • Monitors/Manages nodes within its environment
        • Typically is a trap receiver
    • 1 or more agents
      • Any device or node that has the capability to be managed
    • MIB (Management Information Base)
      • Exposes properties of the agent in a tree-like fashion that can be read and/or written.

    Each SNMP agent belongs to a community, which one or more managers may be a part of. The community, commonly referred to as the community string, is an octet string that is between 0 and 255 ASCII characters in length. Shown below is an outline of what data is transferred within the SNMP message:

    • SNMP Message Definition
      • Version Number - SNMP protocol version
      • Community String -- Octet string that grants access to resources based on community type (i.e. Read, Read/Write, Trap, etc.)
        • Default Read community string: public
        • Default Read/Write community string: private
      • PDU (Protocol Data Unit) - Contains operational instructions and information about the request
        • Get/GetNext/Set Requests
          • Request ID - Sequence number
          • Error Index - Contains which OID (Object Identifier within a MIB tree) has conflicts
          • Error Status - Integer representing the error type
          • OID Item/Value Pair(s) - One or more objects that are part of the request.
            • If the value that is passed is null, the response to the manager contains the value from the agent
            • If the value that is passed it not null, then the agent writes the value corresponding to the OID to the agent
        • Trap Response
          • Triggered OID - Object that breached specified threshold
          • Agent IP Address - IP Address of host
          • Generic ID - Relates to standard trap definitions
          • Specific ID - Relates to proprietary trap definitions
          • Time Stamp - Trap occurrence in time ticks
          • OID Item/Value Pair(s) - Objects that may be passed to the manager if the trap deems it necessary

    The figure below gives a simple illustration on how SNMP operates:

    It's worth noting that this diagram and explanation deals with version 1. The community string passed is in plain text within the message for version 1.0. Versions 2.0 and 3.0 take different measures.

    Management Flow

    The examples above have shown the flow of authentication, message schematic, as well as typical management scenarios. What is shown below is how traffic flows from the manager to the agent, as well as background processing.

    This points out that the manager is capable of three different types of actions in correlation with an agent in its community. Monitoring Intervals and SNMP Operations issue the same kinds of requests to their agents. The reason for separation is because a manager can be in the process of its monitoring interval and still be able to issue requests to agents.

    This is the flow of a standard request that the manager initiates with agents in their communities. The manager makes a request to an agent, in this case a router, which then goes through a series of steps before a response can be sent back.

    • Data parsing and translation - The agent takes the message and parses the information relevant to the request
    • MIB OID correlation - Once the request is authorized, it then takes all the PDUs and correlates the OIDs within them to objects in itself
    • Executes request - Either passes the value of the OID back to the manager or writes the value of the OID associated in the PDU back to the agent
    • Formulates response for manager - Translates the response from the steps above back into a message format for the manager to intercept
    • Send Response - Message is sent to manager for processing and storage

    The manager doesn't always initiate the conversation. The agent is capable of sending a trap, or an event that is triggered when certain criteria is met, to the manager if a specified threshold is surpassed. As you can see from the diagram above, once the trap is triggered a series of steps are executed before a response can be sent to the manager. Information is gathered, placed into a message, and sent to the manager where it then does its own custom processing and data storage.

    Source Code

    Let's start from a basic workspace as shown below:

    As shown above, the project name is NetMgr and the class name is SNMPv1. The first step is to open the project setting menu and alter the Object/library modules field.

    Add snmpapi.lib and mgmtapi.lib to Object/library modules field on this screen. These two files encapsulate all the functions that will be used throughout this tutorial.

    Once that task is completed, the next step is to modify the .IDL file. This tutorial will demonstrate how to create the following four methods: Open, Close, Get and Set. The GUI may be used to add methods by right-mouse clicking on ISNMPv1 interface under the ClassView tab in the project view.

    Below is the actual source within the .IDL file:

    
    // NetMgr.idl : IDL source for NetMgr.dll
    //
    
    // This file will be processed by the MIDL tool to
    // produce the type library (NetMgr.tlb) and marshalling code.
    
    import "oaidl.idl";
    import "ocidl.idl";
    	[
    		object,
    		uuid(EDCC87DE-8C4F-4328-8FFE-B42D0748A3D4),
    		dual,
    		helpstring("ISNMPv1 Interface"),
    		pointer_default(unique)
    	]
    	interface ISNMPv1 : IDispatch
    	{
    	[id(1), helpstring("method Open")] HRESULT Open([in] VARIANT agent,
    		[in]  VARIANT community, [in] int timeout, [in] int retries, [out,retval] BSTR* statusCode);
    	[id(2), helpstring("method Close")] HRESULT Close([out,retval] int* statusCode);
    	[id(3), helpstring("method Get")] HRESULT Get([in] VARIANT oidStr, [out,retval] BSTR* value);
    	[id(4), helpstring("method Set")] HRESULT Set([in] VARIANT oidStr, [in] VARIANT value, [out,retval] BSTR* statusCode);
    	};
    
    [
    	uuid(4C7ED789-E0BD-4BFF-837D-24D48CDB8FA7),
    	version(1.0),
    	helpstring("NetMgr 1.0 Type Library")
    ]
    library NETMGRLib
    {
    	importlib("stdole32.tlb");
    	importlib("stdole2.tlb");
    
    	[
    		uuid(F6BE2804-8969-4370-A43F-1F75560E47F3),
    		helpstring("SNMPv1 Class")
    	]
    	coclass SNMPv1
    	{
    		[default] interface ISNMPv1;
    	};
    };
    
    
    The Open method has four parameters:

    • [in] VARIANT agent - String of the host you are connecting with
    • [in] VARIANT community - Community string for the designated operation
    • [in] int timeout - How long to wait before unsuccessful (in milliseconds)
    • [int] int retries - How many times to try before unsuccessful

    So an example of the call might be: strRetVal = [obj].Open("10.1.1.1", "public", 1000, 3)

    The Get method has the following argument:

    • [in] VARIANT oidStr - The Object Identifier that is being requested
    The Set method has the following parameters:

    • [in] VARIANT oidStr - The Object Identifier that is being requested
    • [in] VARIANT value - The new value for the oidStr

    The Close method has not been listed above because it does not contain any parameters. It simply returns 1 or 0 depending whether or not it could successfully close the session. Here are a few additional items to make note of:

    • GetNext is not listed
    • The arguments for Get and Set will only allow single objects to be accessed.
      • The SNMP specifications allow you to retrieve/update multiple objects at once. For the purpose of keeping this simple, it will not be shown.
    • All values passed back to the caller, except for the Close method, are returned as BSTR and not variants.
    • All IN parameters that could be either a string or integer (or explicitly a string) are declared as VARIANTS.
    Next the SNMPv1.h file must be modified to accommodate both STDMETHOD and global variable declarations:
    
    // SNMPv1.h : Declaration of the CSNMPv1
    
    #ifndef __SNMPV1_H_
    #define __SNMPV1_H_
    
    #define GET     1
    #define GETNEXT 2
    #define SET     5
    
    #define TIMEOUT 2000 /* milliseconds */
    #define RETRIES 3
    
    #define SNMP_BIND_ERROR 1000
    
    #include <wtypes.h>
    #include <stdio.h>
    #include <string.h>
    #include <malloc.h>
    #include <snmp.h>
    #include <mgmtapi.h>
    
    #include "resource.h"       // main symbols
    
    /////////////////////////////////////////////////////////////////////////////
    // CSNMPv1
    class ATL_NO_VTABLE CSNMPv1 : 
    	public CComObjectRootEx<CComSingleThreadModel>,
    	public CComCoClass<CSNMPv1, &CLSID_SNMPv1>,
    	public IDispatchImpl<ISNMPv1, &IID_ISNMPv1, &LIBID_NETMGRLib>
    {
    public:
    	CSNMPv1()
    	{
    	}
    
    DECLARE_REGISTRY_RESOURCEID(IDR_SNMPV1)
    
    DECLARE_PROTECT_FINAL_CONSTRUCT()
    
    BEGIN_COM_MAP(CSNMPv1)
    	COM_INTERFACE_ENTRY(ISNMPv1)
    	COM_INTERFACE_ENTRY(IDispatch)
    END_COM_MAP()
    
    // ISNMPv1
    public:
    STDMETHOD(Set)(/*[in]*/ VARIANT oidStr, /*[in]*/ VARIANT value, /*[out,retval]*/ BSTR *statusCode);
    STDMETHOD(Get)(/*[in]*/ VARIANT oidStr, /*[out,retval]*/ BSTR *value);
    STDMETHOD(Close)(/*[out,retval]*/ int *statusCode);
    STDMETHOD(Open)(/*[in]*/ VARIANT agent, /*[in]*/  VARIANT community,
    	/*[in]*/ int timeout, /*[in]*/ int retries, /*[out,retval]*/ BSTR *statusCode);
    
    private:
    	LPSNMP_MGR_SESSION session; // session placeholder
    	CString lpVal; // utility variable; used for BSTR conversions
    };
    
    #endif //__SNMPV1_H_
    
    
    The session variable is declared here so that the caller is not forced to keep track of it. In the same respect, this also prevents the opening of multiple devices at once. Each session would have to be closed before another one could be opened. In this case, the component could force the caller to keep track of session, or create a multi-dimensional array that correlates session -> host -> host instance.

    The last page to modify will be SNMPv1.cpp, which will house all of the logic for our component. Click here to view the entire SNMPv1.cpp file with in-line comments in every method.

    Conclusion

    This source code should enable any developer to open a connection and make requests to any agent within his community. Even though this is a barebones implementation, there is plenty of room for extending functionality. The resources listed below provide excellent insight into the various aspects of SNMP.

    References

    A Simple Gateway Monitoring Protocol, RFC 1028 by J. Davin, J. Case, M. Fedor and M. Schoffstall

    IAB Recommendations for the Development of Internet Network Management Standards, RFC 1052 by V. Cerf

    Structure and Identification of Management Information for TCP/IP-based Internets, RFC 1065 by M. Rose and K. McCloghrie

    Management Information Base for Network Management for TCP/IP-based Internets, RFC 1066 by K. McCloghrie and M. Rose

    A Simple Network Management Protocol, RFC 1067 by J. Case, M. Fedor, M. Schoffstall and J. Davin

    Structure and Identification of Management Information for TCP/IP-based Internets, RFC 1155 by M. Rose, K. McCloghrie

    A Simple Network Management Protocol (SNMP), RFC 1157 by J. Case, M. Fedor, M. Schoffstall and J. Davin

    Concise MIB Definitions, RFC 1212 by M. Rose and K. McCloghrie

    Management Information Base for Network Management of TCP/IP-based Internets, RFC 1213 by K. McCloghrie and M. Rose

    SNMP : Birth and Evolution by Electronic and Telecommunication Institute of Poland

    SNMP from the LAN Team Tutorial Notes nas.nasa.gov

    About the Author

    Ben Garcia is the Application/Database Team Lead for Prairie Inet, a wireless Internet service provider. In addition to his duties at work, he does freelance Web and application development. Ben has more than 13 years of software development experience in many different facets of the industry. Please feel free to contact Ben at bgarcia@personify.ws.

  • Rate This Article
    Not HelpfulMost Helpful
    1 2 3 4 5
    Other Articles
    Apr 27, 2004 - Develop and Customize Web Parts with Custom Tool Parts
    Tool Parts provide an interface for Web Part properties well beyond the capabilities of the default property pane. In this article Gayan Peiris shows how to customize Web Parts with custom Tool Parts.
    [Read This Article]  [Top]
    Apr 7, 2004 - Reusable Components in ASP.NET 2.0, Object Binding and Precompilation
    This article demonstrates how to create a reusable component in ASP.NET 2.0 and then consume it from an ASP.NET page. Also learn how the ObjectDataSource control can be used to directly bind the output of an object to the controls in an ASP.NET page and how precompilation can be used to increase the performance of the Web application and catch compilation errors.
    [Read This Article]  [Top]
    Mar 31, 2004 - Build a Managed BHO and Plug into the Browser
    Browser Helper Objects (BHOs) are COM components that communicate with Internet Explorer to enrich the browsing experience. Michele Leroux Bustamante returns to the world of COM to show you how to build a managed BHO with the help of the .NET Framework's COM interoperability features.
    [Read This Article]  [Top]
    Feb 18, 2004 - Customizing SharePoint Web Parts with Custom Properties
    In addition to creating custom Web Parts for SharePoint Portal Server, developers can actually create their own custom properties to further enhance Web Part appearance and behavior. Gayan Peiris explains the process and provides all the necessary code.
    [Read This Article]  [Top]
    Sep 26, 2003 - Accessing Shared Resources Using ASP.NET
    Accessing shared resources is a challenge for many ASP.NET developers. Tony Arslan explains how a simple serviced component can solve this infamous problem.
    [Read This Article]  [Top]
    Oct 2, 2002 - Function Pointers and COM
    Using callbacks and function pointers in VB can be risky and complicated. Ben Garcia explains his work-around for the function pointer issue he encountered while creating the VB version of his SNMP component.
    [Read This Article]  [Top]
    Sep 4, 2002 - Creating an SNMP Component - Part 2
    In part two of this intriguing article series, Ben Garcia shows how to build an updated and improved SNMP component in VC++ AND VB, and he briefly explains why limitations in VB make VC++ a better language for developing this type of application.
    [Read This Article]  [Top]
    Jun 26, 2002 - Accessing Caller ID from the Web - Part 1
    Paul Apostolos begins his series on using Web services and the MSComm32.OCX component to access caller id information from a Web page. In part 1, learn how to write the Visual Basic program that runs on the server and updates a database with incoming callers.
    [Read This Article]  [Top]
    Nov 20, 2001 - Creating a Server Component with VB - Redesigned - Part 2
    Doug Dean explains different methods of retrieving and manipulating data from a database in a VB DLL so that it is ready to be rendered in a browser.
    [Read This Article]  [Top]
    Aug 28, 2001 - Create Your Own Visual Basic Add-Ins
    In this article, S.S. Ahmed shows you how to create VB add-ins. Programmers always feel that they are short of several features while working with development tools. Since Microsoft made Visual Basic an extensible product, VB developers can create their own features in VB.
    [Read This Article]  [Top]
    Mailing List
    Want to receive email when the next article is published? Just Click Here to sign up.

    Support the Active Server Industry



    JupiterOnlineMedia

    internet.comearthweb.comDevx.commediabistro.comGraphics.com

    Search:

    Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

    Jupitermedia Corporate Info


    Legal Notices, Licensing, Reprints, & Permissions, Privacy Policy.

    Advertise | Newsletters | Tech Jobs | Shopping | E-mail Offers

    Solutions
    Whitepapers and eBooks
    Microsoft Article: HyperV-The Killer Feature in WinServer ‘08
    Avaya Article: How to Feed Data into the Avaya Event Processor
    Microsoft Article: Install What You Need with Win Server ‘08
    HP eBook: Putting the Green into IT
    Whitepaper: HP Integrated Citrix XenServer for HP ProLiant Servers
    Intel Go Parallel Portal: Interview with C++ Guru Herb Sutter, Part 1
    Intel Go Parallel Portal: Interview with C++ Guru Herb Sutter, Part 2--The Future of Concurrency
    Avaya Article: Setting Up a SIP A/S Development Environment
    IBM Article: How Cool Is Your Data Center?
    Microsoft Article: Managing Virtual Machines with Microsoft System Center
    HP eBook: Storage Networking , Part 1
    Microsoft Article: Solving Data Center Complexity with Microsoft System Center Configuration Manager 2007
    MORE WHITEPAPERS, EBOOKS, AND ARTICLES
    Webcasts
    Intel Video: Are Multi-core Processors Here to Stay?
    On-Demand Webcast: Five Virtualization Trends to Watch
    HP Video: Page Cost Calculator
    Intel Video: APIs for Parallel Programming
    HP Webcast: Storage Is Changing Fast - Be Ready or Be Left Behind
    Microsoft Silverlight Video: Creating Fading Controls with Expression Design and Expression Blend 2
    MORE WEBCASTS, PODCASTS, AND VIDEOS
    Downloads and eKits
    Sun Download: Solaris 8 Migration Assistant
    Sybase Download: SQL Anywhere Developer Edition
    Red Gate Download: SQL Backup Pro and free DBA Best Practices eBook
    Red Gate Download: SQL Compare Pro 6
    Iron Speed Designer Application Generator
    MORE DOWNLOADS, EKITS, AND FREE TRIALS
    Tutorials and Demos
    How-to-Article: Preparing for Hyper-Threading Technology and Dual Core Technology
    eTouch PDF: Conquering the Tyranny of E-Mail and Word Processors
    IBM Article: Collaborating in the High-Performance Workplace
    HP Demo: StorageWorks EVA4400
    Intel Featured Algorhythm: Intel Threading Building Blocks--The Pipeline Class
    Microsoft How-to Article: Get Going with Silverlight and Windows Live
    MORE TUTORIALS, DEMOS AND STEP-BY-STEP GUIDES