Welcome!

Microsoft Cloud Authors: Andreas Grabner, Stackify Blog, Liz McMillan, David H Deans, Automic 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 jimt@bocacom.net.

    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
    SYS-CON Events announced today that Cloud Academy named "Bronze Sponsor" of 21st International Cloud Expo which will take place October 31 - November 2, 2017 at the Santa Clara Convention Center in Santa Clara, CA. Cloud Academy is the industry’s most innovative, vendor-neutral cloud technology training platform. Cloud Academy provides continuous learning solutions for individuals and enterprise teams for Amazon Web Services, Microsoft Azure, Google Cloud Platform, and the most popular cloud com...
    We build IoT infrastructure products - when you have to integrate different devices, different systems and cloud you have to build an application to do that but we eliminate the need to build an application. Our products can integrate any device, any system, any cloud regardless of protocol," explained Peter Jung, Chief Product Officer at Pulzze Systems, in this SYS-CON.tv interview at @ThingsExpo, held November 1-3, 2016, at the Santa Clara Convention Center in Santa Clara, CA
    SYS-CON Events announced today that IBM has been named “Diamond Sponsor” of 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.
    In his session at Cloud Expo, Alan Winters, an entertainment executive/TV producer turned serial entrepreneur, presented a success story of an entrepreneur who has both suffered through and benefited from offshore development across multiple businesses: The smart choice, or how to select the right offshore development partner Warning signs, or how to minimize chances of making the wrong choice Collaboration, or how to establish the most effective work processes Budget control, or how to ma...
    With major technology companies and startups seriously embracing Cloud strategies, now is the perfect time to attend 21st Cloud Expo October 31 - November 2, 2017, at the Santa Clara Convention Center, CA, and June 12-14, 2018, at the Javits Center in New York City, NY, and 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 CA Technologies has been named "Platinum Sponsor" of SYS-CON's 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 planning to development to management to security, CA creates software that fuels transformation for companies in the applic...
    Multiple data types are pouring into IoT deployments. Data is coming in small packages as well as enormous files and data streams of many sizes. Widespread use of mobile devices adds to the total. In this power panel at @ThingsExpo, moderated by Conference Chair Roger Strukhoff, panelists looked at the tools and environments that are being put to use in IoT deployments, as well as the team skills a modern enterprise IT shop needs to keep things running, get a handle on all this data, and deliver...
    In his session at @ThingsExpo, Eric Lachapelle, CEO of the Professional Evaluation and Certification Board (PECB), provided an overview of various initiatives to certify 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 worldwide re...
    Amazon started as an online bookseller 20 years ago. Since then, it has evolved into a technology juggernaut that has disrupted multiple markets and industries and touches many aspects of our lives. It is a relentless technology and business model innovator driving disruption throughout numerous ecosystems. Amazon’s AWS revenues alone are approaching $16B a year making it one of the largest IT companies in the world. With dominant offerings in Cloud, IoT, eCommerce, Big Data, AI, Digital Assista...
    New competitors, disruptive technologies, and growing expectations are pushing every business to both adopt and deliver new digital services. This ‘Digital Transformation’ demands rapid delivery and continuous iteration of new competitive services via multiple channels, which in turn demands new service delivery techniques – including DevOps. In this power panel at @DevOpsSummit 20th Cloud Expo, moderated by DevOps Conference Co-Chair Andi Mann, panelists examined how DevOps helps to meet the de...
    "When we talk about cloud without compromise what we're talking about is that when people think about 'I need the flexibility of the cloud' - it's the ability to create applications and run them in a cloud environment that's far more flexible,” explained Matthew Finnie, CTO of Interoute, in this SYS-CON.tv interview at 20th Cloud Expo, held June 6-8, 2017, at the Javits Center in New York City, NY.
    No hype cycles or predictions of zillions of things here. IoT is big. 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, Associate Partner at M&S Consulting, presented a step-by-step plan to develop your technology implementation strategy. He discussed the evaluation of communication standards and IoT messaging protocols, data analytics considerations, edge-to-cloud tec...
    IoT solutions exploit operational data generated by Internet-connected smart “things” for the purpose of gaining operational insight and producing “better outcomes” (for example, create new business models, eliminate unscheduled maintenance, etc.). The explosive proliferation of IoT solutions will result in an exponential growth in the volume of IoT data, precipitating significant Information Governance issues: who owns the IoT data, what are the rights/duties of IoT solutions adopters towards t...
    With the introduction of IoT and Smart Living in every aspect of our lives, one question has become relevant: What are the security implications? To answer this, first we have to look and explore the security models of the technologies that IoT is founded upon. In his session at @ThingsExpo, Nevi Kaja, a Research Engineer at Ford Motor Company, discussed some of the security challenges of the IoT infrastructure and related how these aspects impact Smart Living. The material was delivered interac...
    The Internet giants are fully embracing AI. All the services they offer to their customers are aimed at drawing a map of the world with the data they get. The AIs from these companies are used to build disruptive approaches that cannot be used by established enterprises, which are threatened by these disruptions. However, most leaders underestimate the effect this will have on their businesses. In his session at 21st Cloud Expo, Rene Buest, Director Market Research & Technology Evangelism at Ara...
    When growing capacity and power in the data center, the architectural trade-offs between server scale-up vs. scale-out continue to be debated. Both approaches are valid: scale-out adds multiple, smaller servers running in a distributed computing model, while scale-up adds fewer, more powerful servers that are capable of running larger workloads. It’s worth noting that there are additional, unique advantages that scale-up architectures offer. One big advantage is large memory and compute capacity...
    Artificial intelligence, machine learning, neural networks. We’re in the midst of a wave of excitement around AI such as hasn’t been seen for a few decades. But those previous periods of inflated expectations led to troughs of disappointment. Will this time be different? Most likely. Applications of AI such as predictive analytics are already decreasing costs and improving reliability of industrial machinery. Furthermore, the funding and research going into AI now comes from a wide range of com...
    Internet of @ThingsExpo, taking place October 31 - November 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA, is co-located with 21st Cloud Expo and will feature technical sessions from a rock star conference faculty and the leading industry players in the world. The Internet of Things (IoT) is the most profound change in personal and enterprise IT since the creation of the Worldwide Web more than 20 years ago. All major researchers estimate there will be tens of billions devic...
    SYS-CON Events announced today that Enzu will exhibit at SYS-CON's 21st Int\ernational Cloud Expo®, which will take place October 31-November 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Enzu’s mission is to be the leading provider of enterprise cloud solutions worldwide. Enzu enables online businesses to use its IT infrastructure to their competitive advantage. By offering a suite of proven hosting and management services, Enzu wants companies to focus on the core of their ...
    SYS-CON Events announced today that GrapeUp, the leading provider of rapid product development at the speed of business, will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place October 31-November 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Grape Up is a software company, specialized in cloud native application development and professional services related to Cloud Foundry PaaS. With five expert teams that operate in various sectors of the market acr...