Welcome!

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

In Part 1 of this series (DNDJ, Vol. 1, issue 5), I described the steps necessary to build a .NET interoperability library to communicate with the Windows SNMP stack. In this article I will build on that foundation by creating the necessary code to support an application capable of receiving and displaying SNMP traps, commonly called an SNMP trap handler. As in Part 1, I will just touch on the more interesting parts of the code and leave you to look at the code to get a complete picture. All of the code for both articles can be downloaded from www.sys-con.com/dotnet/sourcec.cfm.

What Is an SNMP Trap?
An SNMP trap is simply a notification message that is transmitted by an SNMP-managed device whenever it has something of interest to report. Traps can be thought of as event messages, similar to the events in the Windows event logs. Traps, like regular SNMP variables, are defined in MIB (Management Information Base) files. They are defined as a set of SNMP variables contained in (or referenced by) an OID (Object Identifier). If you look at the system directory on any Windows machine that has SNMP installed, you will find several MIB files. (They have the extension ".mib".) If you look through them you will see the variables that are supported on that machine.

Why Are SNMP Traps Needed?
SNMP traps are the primary means of receiving notification of abnormal (or normal) events from SNMP-enabled devices. This makes receiving and interpreting the traps ­ trap monitoring ­ essential to the proper management of a network. Usually, traps are sent to a management system running software capable of receiving the traps, interpreting them, and displaying notification messages in a graphical display. The people at the management center viewing the display are then alerted to the problem. Most management software also has the capability to send alerts to e-mail accounts or pagers.

For simplicity, the trap handler I create here will receive SNMP traps and display them on the console as text messages, but it would be relatively easy to add some logic to interpret the trap and send e-mail or pager alerts when specific conditions are detected.

WinSNMP and Traps
As SNMP has evolved, so has the format of the trap definitions. SNMP v1 and v2 trap formats are different, so they have to be handled in different ways. As I mentioned in Part 1 of this series, WinSNMP supports both v1 and v2 SNMP standards, and it is capable of translating v1 traps into v2 traps, so all we have to do is deal with the SNMP v2 trap format.

Community Strings
One topic I didn't cover in Part 1 is SNMP community strings. Community strings are an attempt to provide some form of security for SNMP. Each time you communicate with an SNMP device you must pass it a community string, which is just a sequence of ASCII characters; you can think of it as a group name. When an SNMP agent receives a request, it tries to match the community string in the request with one it has been configured to accept. If it finds a match, it will proceed with the request. Community strings are also used to restrict or allow write access by defining one community string for read-only access and a different one for read-write access.

SNMP agents also use community strings to identify trap contexts, so an application can look for traps with a specific community string.

Okay, let's get down to business!

Establishing a WinSNMP Session
The first step in any WinSNMP application is to create an SNMP session. We can do this by calling SnmpCreateSession, which tells WinSNMP that our application will need the resources to send and receive SNMP and messages. SnmpCreateSession returns a session handle that we will use when we call other WinSNMP functions.

IntPtr SnmpCreate
Session(IntPtr hwnd,
int msg,
SnmpCallback callback,
IntPtr data);

The key parameter here is the third, callback. This is defined as SnmpCallback, which is defined in our library as a delegate. WinSNMP will use this delegate to call back into our application each time it receives an SNMP trap. To enable this, we create a SnmpCallback delegate and pass it to this function.

SnmpAPI.SnmpCallback SnmpCB = new SnmpAPI.SnmpCallback(OnSnmpMessage);

OnSnmpMessage is the function that will be called with the trap information. It is defined with parameters identical to the declaration of the SnmpCallback delegate.

SNMPAPI_STATUS OnSnmpMessage(IntPtr session,
IntPtr hwnd,
int msg,
uint wparam,
uint lparam,
IntPtr data);

We create the delegate by instantiating a new variable of type SnmpCallback and passing it a parameter reference to OnSnmpMessage.

SnmpCallback SnmpCB = new SnmpAPI.SnmpCallback(OnSnmpMessage);

Now we can pass the SnmpCB variable to SnmpCreateSession.

Registering to Receive Traps
Now that we have a WinSNMP session, the next thing we need to do to receive trap information in our application is register it with the WinSNMP API. This is done using the SnmpRegister function. In the SnmpAPI class library in Part 1, we declared SnmpRegister as:

SNMPAPI_STATUS SnmpRegister(IntPtr session,
IntPtr src,
IntPtr dest,
IntPtr context,
IntPtr notification,
int state);

The parameters allow you to specify the source and destination address of the traps you want to receive, and also to filter them by content. As we will not be using these parameters, I will not go into great detail about them. We will set them all to zero, which tells WinSNMP to send us all traps from all sources.

Receiving the Traps
After the WinSNMP stack is configured, the application is ready to receive traps. With the parameters we have specified, any trap that comes into the computer will end up in our callback function, OnSnmpMessage. In our application, OnSnmpMessage is responsible for receiving the trap message, decoding it, and displaying it to the console. If you want to make it more useful, it would not be much more work to make it take some other action, such as sending an e-mail or page if it detects certain conditions.

The first step in decoding the trap information is to get it from WinSNMP. This is done by calling SnmpRecvMsg.

SNMPAPI_STATUS rc = SnmpAPI.SnmpRecvMsg(session,
out src,
out dest,
out context,
out pdu);

SnmpRecvMsg returns the trap information in four out parameters.

Decoding the Trap Information
Now that we have the trap information, we need to convert it from the SNMP representations into a format we can manipulate. Since we will be displaying this data to the console, we will convert everything to strings.

The source and destination entities (src and dest) are really just IP addresses. To convert them, we call SnmpEntityToStr.

SNMPAPI_STATUS rc = SnmpAPI.SnmpEntityToStr(dest, 1408, buffer);
string source Marshal.PtrToStringAnsi(buffer);

SNMPAPI_STATUS rc = SnmpAPI.SnmpEntityToStr(dest, 1408, buffer);
string source Marshal.PtrToStringAnsi(buffer);

SnmpEntityToStr returns a string representation of the entity reference passed in. The returned string will be the IP address of the device sending the trap (src) and the IP address of the device the trap was sent to (dest). The buffer used in the above code is a work buffer. The creation of this buffer is explained later.

Now we can move on to decoding the actual trap data. All SNMP data is transmitted in what is called a protocol data unit (PDU). You can think of a PDU as a container that holds the SNMP variables. In order to get at the variables in the trap, we need to extract them from the PDU using SnmpGetPduData function. SnmpGetPduData is declared as:

SnmpAPI.SnmpGetPduData(pdu,
out type, out id, out status,
out index, out vbl);

This function will decode the PDU and return the individual data components in the out parameters.

  • type parameter: The type of SNMP message received.
  • id parameter: Will be set to the message id. SNMP is a connectionless protocol, and an application can send multiple messages to an SNMP device before it receives a response. The application must use the id parameter to match the responses to the messages it transmitted.
  • status and index parameters: Used to signal that there was an error in the corresponding SNMP request.
  • vbl parameter: A reference to the variable binding list (vbl). The vbl is just a list of SNMP variable names and their corresponding values.

    Since we are dealing only with traps, we will ignore the id, status, and index parameters. The vbl parameter is the most important, as it contains all of the trap information sent by the SNMP device.

    Displaying the Trap Information
    Now that we have extracted the data components from the trap message given to us by the WinSNMP stack, we can get on with the business of formatting and displaying the trap information to the console.

    First, we must verify that the message we received is actually a trap. In our case this will always be so because we are working only with trap messages in this application. But in a more complicated SNMP application in which you would be sending and receiving SNMP messages as well as traps, you would need a way to tell the difference between a trap message and a message from a device sent in response to an SNMP GET command.

    The type parameter gives us this information, and we should check to see that it is set to the value SNMPAPI_PDU.SNMP_PDU_TRAP. This tells us it is a trap message.

    After we have determined that we have a trap message, we can start to display the trap information. First, we display a header message along with the trap id.

    Console.WriteLine("Trap received...");
    Console.WriteLine("Id: " + id);

    To display the SNMP variables in the vbl, we will need to do a bit more work.

    Decoding the Variable Binding List
    In order to display the information in the variable binding list we first need to get the number of variables that are in the vbl. For this we use the SnmpCountVbl function. SnmpCountVbl takes the vbl as a parameter and returns a count of the number of variables the vbl contains.

    Second, we need to iterate over each variable in the vbl, translate it, then write it to the console. To translate each variable, we need to call SnmpGetVb and pass it the vbl and the index of the variable we are interested in. It will return the name and value of the variable at that position.

    SMIOID name = new SMIOID();
    SMIVALUE val = new SMIVALUE();

    SNMPAPI_STATUS rc = SnmpAPI.SnmpGetVb
    (vbl, index, ref name, ref val);

    Note: The name and value parameters are passed as refs, so you need to initialize them first.

    The next step is to convert the variable name to a string. The variable name is an OID, so we convert it by calling SnmpOidToStr. SnmpOidToStr takes a reference to the OID and returns a string in the buffer specified by the buffer parameter. We must allocate this buffer ourselves ­ but how big does it need to be?

    If we look at the WinSNMP documentation, we see that the largest an OID can be is 1408 bytes, so we allocate a buffer of this size. This might seem like an odd size, but it's not. SNMP uses UDP (User Datagram Protocol) for its transport protocol, and each SNMP message must fit into one UDP message. The standard MTU (Maximum Transmission Unit) on most networks is 1500 bytes, so, 1408 is what's left over when you subtract all the message headers needed to get one variable across the network. We allocate this buffer by calling the .NET marshaler.

    IntPtr buffer = Marshal.AllocHGlobal(1408);

    After we have the buffer, we can call SnmpOidToStr.

    SNMPAPI_STATUS rc = SnmpAPI.SnmpOidToStr(ref oid, 1408, buffer);

    This gives us a string in a global buffer allocated by the marshaler. But all we have is an opaque internal pointer to a buffer. We must convert it to a string type. For this, we call another .NET marshaler function, PtrToStringAnsi.

    string str = Marshal.PtrToStringAnsi(buffer);

    Now we have a string representation of the OID. Whew! All this work and we still haven't decoded the data.

    To convert the data to a displayable format, we need to first check the type of data that was sent in the variable. Each variable value in SNMP includes a type code to help determine the type of data the variable contains. We will use this type to determine how to convert the data to a string. Most of the conversions are straightforward, so I will refer you to the function in Listing 1 that performs the conversions. Most of the conversions are straightforward, but if you look at the string conversion for the SNMP type OCTET_STRING, you will see that in order to determine whether we have an ASCII string or a binary buffer we scan the buffer looking for binary characters. If all the characters are ASCII, we make it a string; If there are binary characters, we encode the buffer so it can be displayed. I chose to unencode it because it was quicker to call the ToBase64String function than to write a hex converter.

    Running the Trap Handler
    If you open the accompanying project in Visual Studio (I have VS.NET 2003, so you will have to make a new project and add the files if you have an earlier version), and run SnmpTrapHandler, you will see the screen shown in Figure 1.

    Now you are ready to receive traps. An easy way to generate a couple of traps is to stop and start the SNMP service on the machine where the trap handler is running. Note that there are two SNMP services, one is called "SNMP Service", and the other is "SNMP Trap Service". You will want to stop "SNMP Service", then restart it. Once you've done this, you should see traps appear in the trap handler console, as shown in Figure 2.

    Conclusion
    That's it. WinSNMP Traps 101. In the future, I will be writing more about SNMP, including how to communicate with and manage real-world devices such as Cisco network equipment.

  • 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.