Welcome!

Microsoft Cloud Authors: Janakiram MSV, Yeshim Deniz, David H Deans, Andreas Grabner, Stackify Blog

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.

WinSNMP
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.3.6.1.2.1.1 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 1.3.6.1.2.1.1.1.0. 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 1.3.6.1.2.1.1.1.0. 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:

iso.org.dod.internet.mgmt.mib-2.system.sysDescr.0

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, 1.3.6.1 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 1.3.6.1.2.1.1.1.0 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;
} smiOCTETS, FAR *smiLPOCTETS;

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.

[StructLayout(LayoutKind.Sequential)]
public struct SMIOCTETS
{
public uint size;
public IntPtr octets;
}

[StructLayout(LayoutKind.Sequential)]
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#.

[StructLayout(LayoutKind.Explicit)]
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.

typedef SNMPAPI_STATUS (CALLBACK *SNMPAPI_CALLBACK)
(IN HSNMP_SESSION hSession,
IN HWND hWnd,
IN UINT wMsg,
IN WPARAM wParam,
IN LPARAM lParam,
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);

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

SNMPAPI_STATUS SNMPAPI_CALL SnmpGetVendorInfo(
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.

VENDORINFO Info;
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:

VENDORINFO Info = new VENDORINFO();
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).

    Conclusion
    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
    The 22nd International Cloud Expo | 1st DXWorld Expo has announced that its Call for Papers is open. Cloud Expo | DXWorld Expo, to be held June 5-7, 2018, at the Javits Center in New York, NY, brings together Cloud Computing, Digital Transformation, Big Data, Internet of Things, DevOps, Machine Learning and WebRTC to one location. With cloud computing driving a higher percentage of enterprise IT budgets every year, it becomes increasingly important to plant your flag in this fast-expanding busin...
    Smart cities have the potential to change our lives at so many levels for citizens: less pollution, reduced parking obstacles, better health, education and more energy savings. Real-time data streaming and the Internet of Things (IoT) possess the power to turn this vision into a reality. However, most organizations today are building their data infrastructure to focus solely on addressing immediate business needs vs. a platform capable of quickly adapting emerging technologies to address future ...
    No hype cycles or predictions of a gazillion things here. IoT is here. You get it. You know your business and have great ideas for a business transformation strategy. What comes next? Time to make it happen. In his session at @ThingsExpo, Jay Mason, an Associate Partner of Analytics, IoT & Cybersecurity at M&S Consulting, presented a step-by-step plan to develop your technology implementation strategy. He also discussed the evaluation of communication standards and IoT messaging protocols, data...
    Nordstrom is transforming the way that they do business and the cloud is the key to enabling speed and hyper personalized customer experiences. In his session at 21st Cloud Expo, Ken Schow, VP of Engineering at Nordstrom, discussed some of the key learnings and common pitfalls of large enterprises moving to the cloud. This includes strategies around choosing a cloud provider(s), architecture, and lessons learned. In addition, he covered some of the best practices for structured team migration an...
    With tough new regulations coming to Europe on data privacy in May 2018, Calligo will explain why in reality the effect is global and transforms how you consider critical data. EU GDPR fundamentally rewrites the rules for cloud, Big Data and IoT. In his session at 21st Cloud Expo, Adam Ryan, Vice President and General Manager EMEA at Calligo, examined the regulations and provided insight on how it affects technology, challenges the established rules and will usher in new levels of diligence arou...
    In his Opening Keynote at 21st Cloud Expo, John Considine, General Manager of IBM Cloud Infrastructure, led attendees through the exciting evolution of the cloud. He looked at this major disruption from the perspective of technology, business models, and what this means for enterprises of all sizes. John Considine is General Manager of Cloud Infrastructure Services at IBM. In that role he is responsible for leading IBM’s public cloud infrastructure including strategy, development, and offering m...
    In his session at 21st Cloud Expo, Raju Shreewastava, founder of Big Data Trunk, provided a fun and simple way to introduce Machine Leaning to anyone and everyone. He solved a machine learning problem and demonstrated an easy way to be able to do machine learning without even coding. Raju Shreewastava is the founder of Big Data Trunk (www.BigDataTrunk.com), a Big Data Training and consulting firm with offices in the United States. He previously led the data warehouse/business intelligence and B...
    Recently, REAN Cloud built a digital concierge for a North Carolina hospital that had observed that most patient call button questions were repetitive. In addition, the paper-based process used to measure patient health metrics was laborious, not in real-time and sometimes error-prone. In their session at 21st Cloud Expo, Sean Finnerty, Executive Director, Practice Lead, Health Care & Life Science at REAN Cloud, and Dr. S.P.T. Krishnan, Principal Architect at REAN Cloud, discussed how they built...
    22nd International Cloud Expo, taking place June 5-7, 2018, at the Javits Center in New York City, NY, and co-located with the 1st DXWorld Expo will feature technical sessions from a rock star conference faculty and the leading industry players in the world. Cloud computing is now being embraced by a majority of enterprises of all sizes. Yesterday's debate about public vs. private has transformed into the reality of hybrid cloud: a recent survey shows that 74% of enterprises have a hybrid cloud ...
    22nd International Cloud Expo, taking place June 5-7, 2018, at the Javits Center in New York City, NY, and co-located with the 1st DXWorld Expo will feature technical sessions from a rock star conference faculty and the leading industry players in the world. Cloud computing is now being embraced by a majority of enterprises of all sizes. Yesterday's debate about public vs. private has transformed into the reality of hybrid cloud: a recent survey shows that 74% of enterprises have a hybrid cloud ...
    DevOps at Cloud Expo – being held June 5-7, 2018, at the Javits Center in New York, NY – announces that its Call for Papers is open. Born out of proven success in agile development, cloud computing, and process automation, DevOps is a macro trend you cannot afford to miss. From showcase success stories from early adopters and web-scale businesses, DevOps is expanding to organizations of all sizes, including the world's largest enterprises – and delivering real results. Among the proven benefits,...
    @DevOpsSummit at Cloud Expo, taking place June 5-7, 2018, at the Javits Center in New York City, NY, is co-located with 22nd Cloud Expo | 1st DXWorld Expo and will feature technical sessions from a rock star conference faculty and the leading industry players in the world. The widespread success of cloud computing is driving the DevOps revolution in enterprise IT. Now as never before, development teams must communicate and collaborate in a dynamic, 24/7/365 environment. There is no time to wait...
    Cloud Expo | DXWorld Expo have announced the conference tracks for Cloud Expo 2018. Cloud Expo will be held June 5-7, 2018, at the Javits Center in New York City, and November 6-8, 2018, at the Santa Clara Convention Center, Santa Clara, CA. Digital Transformation (DX) is a major focus with the introduction of DX Expo within the program. Successful transformation requires a laser focus on being data-driven and on using all the tools available that enable transformation if they plan to survive ov...
    SYS-CON Events announced today that T-Mobile exhibited 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 qua...
    SYS-CON Events announced today that Cedexis will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 - Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Cedexis is the leader in data-driven enterprise global traffic management. Whether optimizing traffic through datacenters, clouds, CDNs, or any combination, Cedexis solutions drive quality and cost-effectiveness. For more information, please visit https://www.cedexis.com.
    SYS-CON Events announced today that Google Cloud has been named “Keynote Sponsor” of SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Companies come to Google Cloud to transform their businesses. Google Cloud’s comprehensive portfolio – from infrastructure to apps to devices – helps enterprises innovate faster, scale smarter, stay secure, and do more with data than ever before.
    SYS-CON Events announced today that Vivint to exhibit at SYS-CON's 21st Cloud Expo, which will take place on October 31 through November 2nd 2017 at the Santa Clara Convention Center in Santa Clara, California. As a leading smart home technology provider, Vivint offers home security, energy management, home automation, local cloud storage, and high-speed Internet solutions to more than one million customers throughout the United States and Canada. The end result is a smart home solution that sav...
    SYS-CON Events announced today that Opsani will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Opsani is the leading provider of deployment automation systems for running and scaling traditional enterprise applications on container infrastructure.
    SYS-CON Events announced today that Nirmata will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Nirmata provides a comprehensive platform, for deploying, operating, and optimizing containerized applications across clouds, powered by Kubernetes. Nirmata empowers enterprise DevOps teams by fully automating the complex operations and management of application containers and its underlying ...
    SYS-CON Events announced today that Opsani to exhibit at SYS-CON's 21st Cloud Expo, which will take place on October 31 through November 2nd 2017 at the Santa Clara Convention Center in Santa Clara, California. Opsani is creating the next generation of automated continuous deployment tools designed specifically for containers. How is continuous deployment different from continuous integration and continuous delivery? CI/CD tools provide build and test. Continuous Deployment is the means by which...