Microsoft Cloud Authors: David H Deans, Liz McMillan, Pat Romanski, Janakiram MSV, Jnan Dash

Related Topics: Microsoft Cloud

Microsoft Cloud: Article

.NET Interop with SNMP

.NET Interop with SNMP

These days it's difficult for anyone involved in IT management to avoid SNMP (Simple Network Management Protocol). It has become the standard management interface for most devices attached to the network. Yet even with its wide adoption, SNMP is sometimes viewed as a "necessary evil" and is thought of as somewhat of a black art. This article will show you how simple SNMP really is, and how you can use it from within the .NET Framework. In this two-part series, I will define an interoperability interface to the WinSNMP API using the features of the .NET interoperability namespace. Then I will create an SNMP trap handler to receive SNMP traps and display them to the console.

The WinSNMP API is a very robust implementation of the SNMP-related RFCs (requests for comments). It supports SNMP v1 and v2c, and implements RFC 2089, which specifies how to convert v1 protocols to v2c. This means that if your application knows how to work with SNMP v2, then it will also be able to talk to all standard v1 devices. If you aren't familiar with the SNMP RFCs, don't worry, you don't need to be to benefit from this article.

The SNMP Standard
While it is not necessary to go into the details of how SNMP works in order to use the Windows SNMP stack, a brief discussion of the basic concepts behind SNMP is in order. The SNMP standard defines two types of information: what data is available on the device (the data definition), and the method for sending or retrieving that data (the protocol definition). The protocol definition describes the format of the communication packets that are used to communicate with SNMP devices. The protocol is handled by the WinSNMP stack and will not be discussed in detail here.

The data definition is stored in one or more files known as MIB (Management Information Base) files. MIB files are the most complex part of SNMP and the most difficult aspect for newcomers to master. I will not go into the details of how the data is defined in an MIB file. Instead, I will describe how data is represented on the device.

SNMP Devices
Each SNMP device contains a set of predefined variables that can be accessed by a management system. The set of variables are grouped into one or more categories, with each category containing one or more related variables. Each variable consists of a name/value pair. For example, the standard SNMP variable that contains the description of a device (the system description) is shown below.

Category Variable name 1

Notice that the category and variable names are actually numbers. Starting from the left, each number defines a subcategory within the previous number, forming a hierarchy of categories. The next number is the variable name. Now comes the tricky part. SNMP manages two basic forms of data, scalar and tabular. Scalar data is a single variable, and tabular data is a table representation (one or more records) containing multiple variables. When requesting a scalar variable, a suffix of ".0" must be appended to the variable name. So, the variable above would be requested as The suffix for tabular data can be any value other than zero (in fact, there can be multiple values separated by dots). I will not go into the details of SNMP tables in this article.

In an SNMP request, the complete name (category + variable name + suffix) is sent to the device. So, the first variable above would be requested as These names are known as OIDs, or Object Identifiers, but I prefer to simply call them what they are, variable names.

For most people it is very hard to remember all these numbers. It would be nice if we had actual names to refer to these variables. This is where the MIB file comes in. One of the functions of the MIB file is to define a unique text name for each variable name. For the foregoing example, the text name is:


The leftmost parts of this name hierarchy have standard numbers (and names) assigned to them by the IETF ( Internet Engineering Task Force). In fact, the first four numbers are always the same for any network device you're likely to encounter. For example, is the name for the Internet category (iso.org.dod.internet ). Virtually all variable names you encounter will be in this category.

Data Types
The SNMP standard defines several messages that a device must support (GET, SET, GETBULK, etc.). Given a valid variable name, I can request the value of the variable by sending an SNMP GET request to the device. If all is well, the device will return the value of the variable. (Similarly, I can set the value of a variable by sending an SNMP SET request.) In order to use this information (to display it, for instance), I first need to know what type of data is in the returned variable.

As mentioned earlier, each variable on the device consists of a name/value pair. For example, the name of the system description variable from my laptop is and its value is "Hardware: x86 Family 15 Model 2 Stepping 4 AT/AT. COMPATIBLE - Software: Windows 2000 Version 5.1 (Build 2600 Uniprocessor Free)."

SNMP reports the data type of this variable as OCTET STRING, which is just another name for a byte array. The array may contain ASCII or binary data. Unfortunately, SNMP does not explicitly define ASCII or binary in a way that is machine readable. You have to look at the MIB definition for the variable to determine that.

Enabling Interoperability
The first step in an interoperability project is the creation of an interoperability layer. In our case, we will need to map the unmanaged C-style constants, structures, and function declarations to the equivalent managed definitions for C# and .NET.

But first, since this is an interoperability project involving unmanaged code (the WinSNMP API), we must decide whether to use unsafe code or not. In some cases the choice is dictated for us by the way the target API is designed. In this case, though, we have a choice. I think it is always better to avoid any unsafe code if possible, so I will show how to define the SNMP interoperability class in a safe coding context.

To get started, we need to take a look at the definition of the unmanaged API. The unmanaged API information for WinSNMP is contained in winsnmp.h, which is included in the Windows Platform SDK. The code for WinSNMP is in wsnmp32.dll. You will need to make sure you have these installed on your system in order to build the project included with this article.

Opening winsnmp.h, you will see that it begins with the necessary C includes and compiler definitions. The next entries define type definitions used by the rest of the file. We are interested only in three sections, the constant definitions, the structure definitions, and the function declarations.

Converting the Constants
Mapping C-style constants to C# enum types is a relatively straightforward process. You need to know only the base type that contains the value. Looking further down the file at the function declarations, we see that all of the constants are passed as 32-bit integer types, although some are signed and some are unsigned. Therefore, our enum types will be either int or uint. After mapping the constants, we end up with the enum definitions in Listing 1.

Converting the Structures
The C-style structure definitions are a bit more complicated. Take a look at the smiVENDORINFO structure from winsnmp.h (see Listing 2). This is a structure of four fixed-length arrays followed by a 32-bit unsigned integer. The equivalent C# structure definition is shown in Listing 3.

First, we must define the basic layout of the structure. For that we use the StructLayout attribute. The StructLayout attribute tells the compiler how the structure definition is to be represented in memory. There are three layout flags.

The LayoutKind.Sequential flag tells the compiler that all members are to be stored in memory in the same order that they are defined in the structure definition, using the default padding. The LayoutKind.Explicit flag tells the compiler that all members are to be stored at the offset specified by their respective FieldOffset attribute. The LayoutKind.Auto flag tells the compiler to store members as it sees fit (this type is not valid for interoperability to unmanaged code).

The mapping of the array members shows some of the amazing flexibility of the .NET marshaler. The WinSNMP documentation states that these members hold ASCII data. It would be nice to be able to map them directly to strings, but .NET needs more information about the arrays and the data they contain before it can automatically convert them to and from the string type. This is where the MarshalAs attribute comes in.

The MarshalAs attribute tells the marshaler how to treat managed types when converting to or from unmanaged code. In order to map our unmanaged char arrays properly, we need to tell the marshaler the size and the type of unmanaged data contained in the buffer. The WinSNMP documentation states that the SnmpGetVendorInfo function returns vendor information in these arrays as zero-terminated strings (C-style strings). The parameter that corresponds to a fixed length C-style string array is UnmanagedType.ByValTStr.

The UnmanagedType.ByValTStr parameter tells the marshaler to convert the managed string to a zero-terminated array of chars. The length of the array is specified in the same attribute with the SizeConst parameter.

Mapping the smiOCTETS and the smiOID structures to C# is a bit easier. These two structure definitions (from winsnmp.h) are shown below.

typedef struct {
smiUINT32 len;
smiLPBYTE ptr;

typedef struct {
smiUINT32 len;
smiLPUINT32 ptr;
} smiOID, FAR *smiLPOID;

As you can see, both of these structures have a 32-bit unsigned integer (len) followed by a pointer to a block of memory, one an array of bytes, the other an array of integers. Also, you will notice that they are variable-length arrays (the length given by the preceding 32-bit integer). The corresponding C# structure definitions are shown here.

public struct SMIOCTETS
public uint size;
public IntPtr octets;

public struct SMIOID
public uint size;
public IntPtr dwords;

As you can see, the len member maps directly to a base type (uint), but the pointer member is mapped to an IntPtr. The IntPtr type is used when you have an opaque 32-bit value, either a pointer (equivalent to a void* in C), or a handle (such as an HWND). In our case, because the size of the array is stored in a separate member, and because the marshaling attributes in .NET don't allow us to specify that the size for one member is the value of another (actually it does, but only for COM clients), we must declare it as an IntPtr and explicitly handle the marshaling of the data in our code.

The last structure we need to convert is also the most complicated. The smiVALUE structure has two members. The first is a 32-bit unsigned integer that specifies the type of value contained within the structure. The second member is a C union of variables that contain the value.

Unions in .NET
How do we marshal a union? Fortunately, this is rather simple to do. First, we have to define the StructLayout attribute using a parameter of LayoutKind.Explicit. This allows us to define the exact position of each member in the structure using the FieldOffset attribute, as shown in Listing 4

As you can see, all members are defined with an offset of zero. This tells the compiler to map each member starting at the first byte in the structure, overlaying all members (as in a C union). Now that we have the union definition, we can convert the smiVALUE structure to C#.

public struct SMIVALUE
[FieldOffset(0)] public SNMPAPI_SYNTAX type;
[FieldOffset(4)] public SMIVUNION val;

There is one more detail about the SMIVALUE structure definition I should mention. In release 1.0 of the .NET Framework, defining the layout of a structure as LayoutKind.Explicit meant that it could not be contained in another structure that was defined as LayoutKind.Sequential. This necessitated the use of LayoutKind.Explicit on the SMIVALUE structure. This appears to have been fixed in version 1.1, but I left the explicit definition for backward compatibility.

Converting the Functions
Now that we have enum and structure definitions, we need to write the function declarations. I will explain two function declarations that are representative of the issues you will encounter during the conversion of the WinSNMP functions.

Going back to winsnmp.h, we see that the first function declaration is actually a type definition defining a callback function. When you register your application with WinSNMP, you can choose the type of delivery mechanism you would like for received SNMP messages. You can either have WinSNMP send them to a window as a specific Windows message, or you can define a callback function that is to receive the messages. Personally, I prefer to go with the most efficient option, a callback.

Defining a WinSNMP Callback
Callbacks are defined in C# using the delegate keyword. A delegate declares a contract between you and the caller.

IN LPVOID lpClientData);

As you can see, the callback definition from winsnmp.h is just a definition of a pointer to a function. The corresponding C# delegate declaration is shown below. Notice the use of IntPtr for all handle and opaque memory pointers.

public delegate SNMPAPI_STATUS SnmpCallback(
IntPtr session,
IntPtr hwnd,
int msg,
uint wparam,
uint lparam,
IntPtr data);

The next function we will convert is SnmpGetVendorInfo. From winsnmp.h:

OUT smiLPVENDORINFO vendorInfo);

This function seems simple at first, but there are some interop issues that you should be aware of when converting any C-style functions. A first try at conversion might be:

public static extern SNMPAPI_STATUS
SnmpGetVendorInfo(out VENDORINFO Info);

SnmpGetVendorInfo takes a pointer to a VENDORINFO and fills in the structure it points to with information describing the vendor of the SNMP stack. Given this definition, it may seem reasonable to define Info as an out parameter. However, defining Info as an out parameter may or may not cause problems when this function is actually called. The C# compiler does not enforce variable initialization for out parameters, so it would happily allow you to pass an uninitialized VENDORINFO variable to the function.

SnmpGetVendorInfo(out info);

Since the function is expecting a pointer to an existing structure, it would happily corrupt your managed heap. However, if you initialized the VENDORINFO variable first, all would be fine:

SnmpGetVendorInfo(out info);

This problem can be prevented by declaring Info as a ref parameter, and the compiler will make sure you pass an initialized parameter.

public static extern SNMPAPI_STATUS
SnmpGetVendorInfo(ref VENDORINFO Info);

A few general rules I applied when converting the WinSNMP function declarations:

  • All handle parameters and opaque pointers (void*) map to IntPtr.
  • Define all structure parameters (in or out) as ref parameters. The in parameters passed as refs avoid a structure copy; the out parameters must be ref.
  • All C-style string parameters map to the string type with an appropriate MarshalAs attribute (MarshalAs(UnmanagedType.LPStr)).
  • All value type in parameters (int, uint, etc.) are passed by value (no ref keyword), and all value type out parameters (int*, etc) are passed by reference (out keyword), in/out value parameters are passed by reference (ref keyword).

    Well, that's it! Now that we have the interoperability layer, we can write an SNMP management application that uses it. In a future issue, I will present an SNMP trap handler that receives SNMP trap notifications and displays them on the console.

  • More Stories By James R. Thomas

    Jim Thomas is a Telecommunications Software Consultant for SIEMENS and Operating Manager at Bocacom.net. His spends his spare time developing distributed network management tools using .NET. His wife can?t remember what he looks like. He can be reached at [email protected]

    Comments (0)

    Share your thoughts on this story.

    Add your comment
    You must be signed in to add a comment. Sign-in | Register

    In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.

    @ThingsExpo Stories
    Your homes and cars can be automated and self-serviced. Why can't your storage? From simply asking questions to analyze and troubleshoot your infrastructure, to provisioning storage with snapshots, recovery and replication, your wildest sci-fi dream has come true. In his session at @DevOpsSummit at 20th Cloud Expo, Dan Florea, Director of Product Management at Tintri, will provide a ChatOps demo where you can talk to your storage and manage it from anywhere, through Slack and similar services ...
    SYS-CON Events announced today that Ocean9will exhibit at SYS-CON's 20th International Cloud Expo®, which will take place on June 6-8, 2017, at the Javits Center in New York City, NY. Ocean9 provides cloud services for Backup, Disaster Recovery (DRaaS) and instant Innovation, and redefines enterprise infrastructure with its cloud native subscription offerings for mission critical SAP workloads.
    The taxi industry never saw Uber coming. Startups are a threat to incumbents like never before, and a major enabler for startups is that they are instantly “cloud ready.” If innovation moves at the pace of IT, then your company is in trouble. Why? Because your data center will not keep up with frenetic pace AWS, Microsoft and Google are rolling out new capabilities In his session at 20th Cloud Expo, Don Browning, VP of Cloud Architecture at Turner, will posit that disruption is inevitable for c...
    SYS-CON Events announced today that SoftLayer, an IBM Company, has been named “Gold Sponsor” of SYS-CON's 18th Cloud Expo, which will take place on June 7-9, 2016, at the Javits Center in New York, New York. SoftLayer, an IBM Company, provides cloud infrastructure as a service from a growing number of data centers and network points of presence around the world. SoftLayer’s customers range from Web startups to global enterprises.
    SYS-CON Events announced today that Conference Guru has been named “Media Sponsor” of SYS-CON's 20th International Cloud Expo, which will take place on June 6–8, 2017, at the Javits Center in New York City, NY. A valuable conference experience generates new contacts, sales leads, potential strategic partners and potential investors; helps gather competitive intelligence and even provides inspiration for new products and services. Conference Guru works with conference organizers to pass great dea...
    SYS-CON Events announced today that Technologic Systems Inc., an embedded systems solutions company, will exhibit at SYS-CON's @ThingsExpo, which will take place on June 6-8, 2017, at the Javits Center in New York City, NY. Technologic Systems is an embedded systems company with headquarters in Fountain Hills, Arizona. They have been in business for 32 years, helping more than 8,000 OEM customers and building over a hundred COTS products that have never been discontinued. Technologic Systems’ pr...
    SYS-CON Events announced today that CA Technologies has been named “Platinum Sponsor” of SYS-CON's 20th International Cloud Expo®, which will take place on June 6-8, 2017, at the Javits Center in New York City, NY, and the 21st International Cloud Expo®, which will take place October 31-November 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. CA Technologies helps customers succeed in a future where every business – from apparel to energy – is being rewritten by software. From ...
    With major technology companies and startups seriously embracing Cloud strategies, now is the perfect time to attend @CloudExpo | @ThingsExpo, June 6-8, 2017, at the Javits Center in New York City, NY and October 31 - November 2, 2017, Santa Clara Convention Center, CA. Learn what is going on, contribute to the discussions, and ensure that your enterprise is on the right path to Digital Transformation.
    SYS-CON Events announced today that Telecom Reseller has been named “Media Sponsor” of SYS-CON's 20th International Cloud Expo, which will take place on June 6–8, 2017, at the Javits Center in New York City, NY. Telecom Reseller reports on Unified Communications, UCaaS, BPaaS for enterprise and SMBs. They report extensively on both customer premises based solutions such as IP-PBX as well as cloud based and hosted platforms.
    SYS-CON Events announced today that Loom Systems will exhibit at SYS-CON's 20th International Cloud Expo®, which will take place on June 6-8, 2017, at the Javits Center in New York City, NY. Founded in 2015, Loom Systems delivers an advanced AI solution to predict and prevent problems in the digital business. Loom stands alone in the industry as an AI analysis platform requiring no prior math knowledge from operators, leveraging the existing staff to succeed in the digital era. With offices in S...
    SYS-CON Events announced today that Interoute, owner-operator of one of Europe's largest networks and a global cloud services platform, has been named “Bronze Sponsor” of SYS-CON's 20th Cloud Expo, which will take place on June 6-8, 2017 at the Javits Center in New York, New York. Interoute is the owner-operator of one of Europe's largest networks and a global cloud services platform which encompasses 12 data centers, 14 virtual data centers and 31 colocation centers, with connections to 195 add...
    SYS-CON Events announced today that T-Mobile will exhibit at SYS-CON's 20th International Cloud Expo®, which will take place on June 6-8, 2017, at the Javits Center in New York City, NY. As America's Un-carrier, T-Mobile US, Inc., is redefining the way consumers and businesses buy wireless services through leading product and service innovation. The Company's advanced nationwide 4G LTE network delivers outstanding wireless experiences to 67.4 million customers who are unwilling to compromise on ...
    In his session at @ThingsExpo, Eric Lachapelle, CEO of the Professional Evaluation and Certification Board (PECB), will provide an overview of various initiatives to certifiy the security of connected devices and future trends in ensuring public trust of IoT. Eric Lachapelle is the Chief Executive Officer of the Professional Evaluation and Certification Board (PECB), an international certification body. His role is to help companies and individuals to achieve professional, accredited and worldw...
    SYS-CON Events announced today that Infranics will exhibit at SYS-CON's 20th International Cloud Expo®, which will take place on June 6-8, 2017, at the Javits Center in New York City, NY. Since 2000, Infranics has developed SysMaster Suite, which is required for the stable and efficient management of ICT infrastructure. The ICT management solution developed and provided by Infranics continues to add intelligence to the ICT infrastructure through the IMC (Infra Management Cycle) based on mathemat...
    SYS-CON Events announced today that SD Times | BZ Media has been named “Media Sponsor” of SYS-CON's 20th International Cloud Expo, which will take place on June 6–8, 2017, at the Javits Center in New York City, NY. BZ Media LLC is a high-tech media company that produces technical conferences and expositions, and publishes a magazine, newsletters and websites in the software development, SharePoint, mobile development and commercial UAV markets.
    SYS-CON Events announced today that Cloudistics, an on-premises cloud computing company, has been named “Bronze Sponsor” of SYS-CON's 20th International Cloud Expo®, which will take place on June 6-8, 2017, at the Javits Center in New York City, NY. Cloudistics delivers a complete public cloud experience with composable on-premises infrastructures to medium and large enterprises. Its software-defined technology natively converges network, storage, compute, virtualization, and management into a ...
    Now that the world has connected “things,” we need to build these devices as truly intelligent in order to create instantaneous and precise results. This means you have to do as much of the processing at the point of entry as you can: at the edge. The killer use cases for IoT are becoming manifest through AI engines on edge devices. An autonomous car has this dual edge/cloud analytics model, producing precise, real-time results. In his session at @ThingsExpo, John Crupi, Vice President and Eng...
    SYS-CON Events announced today that HTBase will exhibit at SYS-CON's 20th International Cloud Expo®, which will take place on June 6-8, 2017, at the Javits Center in New York City, NY. HTBase (Gartner 2016 Cool Vendor) delivers a Composable IT infrastructure solution architected for agility and increased efficiency. It turns compute, storage, and fabric into fluid pools of resources that are easily composed and re-composed to meet each application’s needs. With HTBase, companies can quickly prov...
    There are 66 million network cameras capturing terabytes of data. How did factories in Japan improve physical security at the facilities and improve employee productivity? Edge Computing reduces possible kilobytes of data collected per second to only a few kilobytes of data transmitted to the public cloud every day. Data is aggregated and analyzed close to sensors so only intelligent results need to be transmitted to the cloud. Non-essential data is recycled to optimize storage.
    "I think that everyone recognizes that for IoT to really realize its full potential and value that it is about creating ecosystems and marketplaces and that no single vendor is able to support what is required," explained Esmeralda Swartz, VP, Marketing Enterprise and Cloud at Ericsson, in this SYS-CON.tv interview at @ThingsExpo, held June 7-9, 2016, at the Javits Center in New York City, NY.