Welcome!

Microsoft Cloud Authors: Pat Romanski, Andreas Grabner, Nick Basinger, Kevin Benedict, Liz McMillan

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.


    IoT & Smart Cities Stories
    Moroccanoil®, the global leader in oil-infused beauty, is thrilled to announce the NEW Moroccanoil Color Depositing Masks, a collection of dual-benefit hair masks that deposit pure pigments while providing the treatment benefits of a deep conditioning mask. The collection consists of seven curated shades for commitment-free, beautifully-colored hair that looks and feels healthy.
    The textured-hair category is inarguably the hottest in the haircare space today. This has been driven by the proliferation of founder brands started by curly and coily consumers and savvy consumers who increasingly want products specifically for their texture type. This trend is underscored by the latest insights from NaturallyCurly's 2018 TextureTrends report, released today. According to the 2018 TextureTrends Report, more than 80 percent of women with curly and coily hair say they purcha...
    The textured-hair category is inarguably the hottest in the haircare space today. This has been driven by the proliferation of founder brands started by curly and coily consumers and savvy consumers who increasingly want products specifically for their texture type. This trend is underscored by the latest insights from NaturallyCurly's 2018 TextureTrends report, released today. According to the 2018 TextureTrends Report, more than 80 percent of women with curly and coily hair say they purcha...
    We all love the many benefits of natural plant oils, used as a deap treatment before shampooing, at home or at the beach, but is there an all-in-one solution for everyday intensive nutrition and modern styling?I am passionate about the benefits of natural extracts with tried-and-tested results, which I have used to develop my own brand (lemon for its acid ph, wheat germ for its fortifying action…). I wanted a product which combined caring and styling effects, and which could be used after shampo...
    The platform combines the strengths of Singtel's extensive, intelligent network capabilities with Microsoft's cloud expertise to create a unique solution that sets new standards for IoT applications," said Mr Diomedes Kastanis, Head of IoT at Singtel. "Our solution provides speed, transparency and flexibility, paving the way for a more pervasive use of IoT to accelerate enterprises' digitalisation efforts. AI-powered intelligent connectivity over Microsoft Azure will be the fastest connected pat...
    There are many examples of disruption in consumer space – Uber disrupting the cab industry, Airbnb disrupting the hospitality industry and so on; but have you wondered who is disrupting support and operations? AISERA helps make businesses and customers successful by offering consumer-like user experience for support and operations. We have built the world’s first AI-driven IT / HR / Cloud / Customer Support and Operations solution.
    Codete accelerates their clients growth through technological expertise and experience. Codite team works with organizations to meet the challenges that digitalization presents. Their clients include digital start-ups as well as established enterprises in the IT industry. To stay competitive in a highly innovative IT industry, strong R&D departments and bold spin-off initiatives is a must. Codete Data Science and Software Architects teams help corporate clients to stay up to date with the mod...
    At CloudEXPO Silicon Valley, June 24-26, 2019, Digital Transformation (DX) is a major focus with expanded DevOpsSUMMIT and FinTechEXPO programs within the DXWorldEXPO agenda. 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 over the long term. A total of 88% of Fortune 500 companies from a generation ago are now out of business. Only 12% still survive. Similar percentages are found throug...
    Druva is the global leader in Cloud Data Protection and Management, delivering the industry's first data management-as-a-service solution that aggregates data from endpoints, servers and cloud applications and leverages the public cloud to offer a single pane of glass to enable data protection, governance and intelligence-dramatically increasing the availability and visibility of business critical information, while reducing the risk, cost and complexity of managing and protecting it. Druva's...
    BMC has unmatched experience in IT management, supporting 92 of the Forbes Global 100, and earning recognition as an ITSM Gartner Magic Quadrant Leader for five years running. Our solutions offer speed, agility, and efficiency to tackle business challenges in the areas of service management, automation, operations, and the mainframe.