SNMP version 2 packet class.
Available packet classes are:
  • SnmpV1Packet
  • SnmpV1TrapPacket
  • SnmpV2Packet
  • SnmpV3Packet
This class is provided to simplify encoding and decoding of packets and to provide consistent interface for users who wish to handle transport part of protocol on their own without using the UdpTarget class. SnmpPacket and derived classes have been developed to implement SNMP version 1, 2 and 3 packet support. For SNMP version 1 and 2 packet, SnmpV1Packet and SnmpV2Packet classes provides sufficient support for encoding and decoding data to/from BER buffers to satisfy requirements of most applications. SNMP version 3 on the other hand requires a lot more information to be passed to the encoder method and returned by the decode method. While using SnmpV3Packet class for full packet handling is possible, transport specific class UdpTarget uses SecureAgentParameters class to store protocol version 3 specific information that carries over from request to request when used on the same SNMP agent and therefore simplifies both initial definition of agents configuration (mostly security) as well as removes the need for repeated initialization of the packet class for subsequent requests. If you decide not to use transport helper class(es) like UdpTarget, BER encoding and decoding and packets is easily done with SnmpPacket derived classes. Example, SNMP version 2 packet encoding: SnmpV2Packet packetv2 = new SnmpV2Packet(); packetv2.Community.Set("public"); packetv2.Pdu.Set(mypdu); byte[] berpacket = packetv2.encode(); Example, SNMP version 2 packet decoding: SnmpV2Packet packetv2 = new SnmpV2Packet(); packetv2.decode(inbuffer,inlen);
Inheritance: SnmpPacket
Example #1
0
        /// <summary>Validate received reply</summary>
        /// <param name="packet">Received SNMP packet</param>
        /// <returns>True if packet is validated, otherwise false</returns>
        public bool ValidateReceivedPacket(SnmpPacket packet)
        {
            if (packet.Version != version)
            {
                return(false);
            }

            if (version == ESnmpVersion.Ver1)
            {
                SnmpV1Packet pkt = packet as SnmpV1Packet;
                if (pkt.Community.Equals(community))
                {
                    return(true);
                }
            }

            if (version == ESnmpVersion.Ver2)
            {
                SnmpV2Packet pkt = packet as SnmpV2Packet;
                if (pkt.Community.Equals(community))
                {
                    return(true);
                }
            }

            return(false);
        }
Example #2
0
        /// <summary>
        /// Build SNMP RESPONSE packet for the INFORM packet class.
        /// </summary>
        /// <param name="informPacket">SNMP INFORM packet</param>
        /// <returns>SNMP version 2 packet containing RESPONSE to the INFORM packet contained in the parameter.</returns>
        /// <exception cref="SnmpInvalidPduTypeException">Parameter is not an INFORM SNMP version 2 packet class</exception>
        /// <exception cref="SnmpInvalidVersionException">Parameter is not a SNMP version 2 packet</exception>
        public static SnmpV2Packet BuildInformResponse(SnmpV2Packet informPacket)
        {
            if (informPacket.Version != SnmpVersion.Ver2)
            {
                throw new SnmpInvalidVersionException("INFORM packet can only be parsed from an SNMP version 2 packet.");
            }

            if (informPacket.Pdu.Type != PduType.Inform)
            {
                throw new SnmpInvalidPduTypeException("Inform response can only be built for INFORM packets.");
            }

            SnmpV2Packet response = new SnmpV2Packet(informPacket.Community.ToString());

            response.Pdu.Type = PduType.Response;
            response.Pdu.TrapObjectID.Set(informPacket.Pdu.TrapObjectID);
            response.Pdu.TrapSysUpTime.Value = informPacket.Pdu.TrapSysUpTime.Value;
            foreach (Vb v in informPacket.Pdu.VbList)
            {
                response.Pdu.VbList.Add(v.Oid, v.Value);
            }
            response.Pdu.RequestId = informPacket.Pdu.RequestId;

            return(response);
        }
 /// <summary>
 /// Send SNMP version 2 Trap notification
 /// </summary>
 /// <param name="packet">SNMP v2 Trap packet class</param>
 /// <param name="peer">Manager (receiver) IP address</param>
 /// <param name="port">Manager (receiver) UDP port number</param>
 public void SendV2Trap(SnmpV2Packet packet, IpAddress peer, int port)
 {
     if (packet.Pdu.Type != PduType.V2Trap)
     {
         throw new SnmpInvalidPduTypeException("Invalid Pdu type.");
     }
     byte[] outBuffer = packet.encode();
     _sock.SendTo(outBuffer, new IPEndPoint((IPAddress)peer, port));
 }
        /// <summary>
        /// Construct and send SNMP v2 Trap
        /// </summary>
        /// <param name="receiver">Trap receiver IP address</param>
        /// <param name="receiverPort">Trap receiver UDP port number</param>
        /// <param name="community">SNMP community name</param>
        /// <param name="senderUpTime">Sender sysUpTime</param>
        /// <param name="trapObjectID">Trap ObjectID</param>
        /// <param name="varList">Variable binding list</param>
        public void SendV2Trap(IpAddress receiver, int receiverPort, string community, UInt32 senderUpTime,
                               Oid trapObjectID, VbCollection varList)
        {
            SnmpV2Packet packet = new SnmpV2Packet(community);

            packet.Pdu.Type                = PduType.V2Trap;
            packet.Pdu.TrapObjectID        = trapObjectID;
            packet.Pdu.TrapSysUpTime.Value = senderUpTime;
            packet.Pdu.SetVbList(varList);
            SendV2Trap(packet, receiver, receiverPort);
        }
 /// <summary>
 /// Initialize SNMP packet class with agent parameters. In this class, SNMP community name is
 /// set in SNMPv1 and SNMPv2 packets.
 /// </summary>
 /// <param name="packet">Packet class to initialize</param>
 public void InitializePacket(SnmpPacket packet)
 {
     if (packet is SnmpV1Packet)
     {
         SnmpV1Packet pkt = (SnmpV1Packet)packet;
         pkt.Community.Set(_community);
     }
     else if (packet is SnmpV2Packet)
     {
         SnmpV2Packet pkt = (SnmpV2Packet)packet;
         pkt.Community.Set(_community);
     }
     else
     {
         throw new SnmpInvalidVersionException("Invalid SNMP version.");
     }
 }
Example #6
0
 /// <summary>
 /// Prepare packet for transmission by filling target specific information in the packet.
 /// </summary>
 /// <param name="packet">SNMP packet class for the required version</param>
 /// <returns>True if packet values are correctly set, otherwise false.</returns>
 public bool PreparePacketForTransmission(SnmpPacket packet)
 {
     if (packet.Version != _version)
     {
         return(false);
     }
     if (_version == SnmpVersion.Ver1)
     {
         SnmpV1Packet pkt = (SnmpV1Packet)packet;
         pkt.Community.Set(_community);
         return(true);
     }
     else if (_version == SnmpVersion.Ver2)
     {
         SnmpV2Packet pkt = (SnmpV2Packet)packet;
         pkt.Community.Set(_community);
         return(true);
     }
     return(false);
 }
Example #7
0
        public Trap(string ip, SnmpV2Packet pckt)
        {
            tIPAddress = ip;
            tTime =  getTime();
            tCommunity = pckt.Community.ToString();
            trapSource = pckt.Pdu.ToString();
            trapID = getMD5Hash(trapSource);
               sourcePacket = pckt;

            Parser parseMe = new Parser();
            //загрузим парсер
            parseMe.loadFromFile();

            foreach (ParserRule rls in parseMe.ruleList)
            {
                //попытаемся добавить каждый оид из указанных в парсере
                fields[rls.param] = getTrapByOID(pckt, rls.oid,rls.textPattern);
               // MessageBox.Show("add to trap: " + rls.name + " " + rls.oid + "--" + fields[rls.param]);
            }

            //MessageBox.Show(trapSource);
        }
Example #8
0
        /// <summary>Prepare packet for transmission by filling target specific information in the packet.</summary>
        /// <param name="packet">SNMP packet class for the required version</param>
        /// <returns>True if packet values are correctly set, otherwise false.</returns>
        public bool PreparePacketForTransmission(SnmpPacket packet)
        {
            if (packet.Version != version)
            {
                return(false);
            }

            if (version == ESnmpVersion.Ver1)
            {
                SnmpV1Packet pkt = packet as SnmpV1Packet;
                pkt.Community.Set(community);
                return(true);
            }

            if (version == ESnmpVersion.Ver2)
            {
                SnmpV2Packet pkt = packet as SnmpV2Packet;
                pkt.Community.Set(community);
                return(true);
            }

            return(false);
        }
Example #9
0
 /// <summary>
 /// Validate received reply
 /// </summary>
 /// <param name="packet">Received SNMP packet</param>
 /// <returns>True if packet is validated, otherwise false</returns>
 public bool ValidateReceivedPacket(SnmpPacket packet)
 {
     if (packet.Version != _version)
     {
         return(false);
     }
     if (_version == SnmpVersion.Ver1)
     {
         SnmpV1Packet pkt = (SnmpV1Packet)packet;
         if (pkt.Community.Equals(_community))
         {
             return(true);
         }
     }
     else if (_version == SnmpVersion.Ver2)
     {
         SnmpV2Packet pkt = (SnmpV2Packet)packet;
         if (pkt.Community.Equals(_community))
         {
             return(true);
         }
     }
     return(false);
 }
Example #10
0
        internal void AsyncResponse(AsyncRequestResult result, IPEndPoint peer, byte[] buffer, int buflen)
        {
            if (result != AsyncRequestResult.NoError)
            {
                _response(result, null);
            }
            else
            {
                if (buffer == null || buffer.Length <= 0 || buflen <= 0)
                {
                    _response(AsyncRequestResult.NoDataReceived, null);
                    return;
                }
                // verify packet
                if (_agentParameters.Version == (int)SnmpVersion.Ver1)
                {
                    SnmpV1Packet packet = new SnmpV1Packet();
                    try
                    {
                        packet.decode(buffer, buflen);
                    }
                    catch(Exception ex)
                    {
                        ex.GetType();
                        // Console.WriteLine("Exception while decoding SNMP packet: " + ex.ToString());
                        _response(AsyncRequestResult.DecodeError, packet);
                        return;
                    }
                    _response(AsyncRequestResult.NoError, packet);
                    return;
                }
                else if (_agentParameters.Version == SnmpVersion.Ver2)
                {
                    SnmpV2Packet packet = new SnmpV2Packet();
                    try
                    {
                        packet.decode(buffer, buflen);
                    }
                    catch (Exception ex)
                    {
                        ex.GetType();
                        // Console.WriteLine("Exception while decoding SNMP packet: " + ex.ToString());
                        // MutableByte b = new MutableByte(buffer, buflen);
                        // Console.WriteLine("Buffer length {0}", buflen);
                        // SnmpConstants.DumpHex(b);
                        _response(AsyncRequestResult.DecodeError, packet);
                        return;
                    }

                    _response(AsyncRequestResult.NoError, packet);
                }
                else if (_agentParameters.Version == SnmpVersion.Ver3)
                {
                    SnmpV3Packet packet = new SnmpV3Packet();
                    SecureAgentParameters secparams = (SecureAgentParameters)_agentParameters;
                    secparams.InitializePacket(packet);
                    try {
                        if (secparams.HasCachedKeys)
                            packet.decode(buffer, buflen, secparams.AuthenticationKey, secparams.PrivacyKey);
                        else
                            packet.decode(buffer, buflen);
                    }
                    catch
                    {
                        _response(AsyncRequestResult.DecodeError, packet);
                        return;
                    }
                    if (!secparams.ValidateIncomingPacket(packet))
                    {
                        _response(AsyncRequestResult.AuthenticationError, packet);
                    }
                    else
                    {
                        secparams.UpdateDiscoveryValues(packet); // update time, etc. values
                        _response(AsyncRequestResult.NoError, packet);
                    }
                }
            }
        }
Example #11
0
        /// <summary>Make SNMP Request</summary>
        /// <remarks>
        /// Make SNMP request. With this method you can make blocked SNMP version 1, 2 and 3 requests of type GET,
        /// GET-NEXT, GET-BULK, SET and REPORT (request types have to compatible with the SNMP protocol version you
        /// are using).
        /// 
        /// This method will pass through any exceptions thrown by parsing classes/methods so see individual packet
        /// classes, ASN.1 type classes, authentication, privacy, etc. classes for exceptions thrown.
        /// </remarks>
        /// <param name="pdu">Pdu class (do not pass ScopedPdu)</param>
        /// <param name="agentParameters">Security information for the request. Use <see cref="AgentParameters"/>
        /// for SNMP versions 1 and 2 requests. Use <see cref="SecureAgentParameters"/> for SNMP version 3
        /// requests.</param>
        /// <returns>Appropriate SNMP packet class for the reply received (<see cref="SnmpV1Packet"/>, 
        /// <see cref="SnmpV2Packet"/>, or <see cref="SnmpV3Packet"/>. Null value if there was an error
        /// with the request.</returns>
        /// <exception cref="SnmpAuthenticationException">Thrown on SNMPv3 requests when authentication password
        /// is not specified on authNoPriv or authPriv requests in SecureAgentParameters or if incoming packet 
        /// authentication check failed.
        /// 
        /// With SNMP ver1 and ver2c, authentication check fails when invalid community name is parsed in the reply.</exception>
        /// <exception cref="SnmpPrivacyException">Thrown on SNMPv3 requests when privacy password is not
        /// specified in SecureAgentParameters on authPriv requests.</exception>
        /// <exception cref="SnmpException">Thrown in following cases:
        /// 
        /// * IAgentParameters.Valid() returned false. SnmpException.ErrorCode is set to SnmpException.InvalidIAgentParameters
        /// * No data received on request. SnmpException.ErrorCode is set to SnmpException.NoDataReceived
        /// * Invalid RequestId in reply. SnmpException.ErrorCode is set to SnmpException.InvalidRequestId
        /// </exception>
        public SnmpPacket Request(Pdu pdu, IAgentParameters agentParameters)
        {
            byte[] outPacket;
            if (agentParameters.Version == SnmpVersion.Ver3)
            {
                SecureAgentParameters secparams = (SecureAgentParameters)agentParameters;
                if (secparams.Authentication != AuthenticationDigests.None && secparams.AuthenticationSecret.Length <= 0)
                    throw new SnmpAuthenticationException("Authentication password not specified.");
                if (secparams.Privacy != PrivacyProtocols.None && secparams.PrivacySecret.Length <= 0)
                    throw new SnmpPrivacyException("Privacy password not specified.");
                _noSourceCheck = false; // this option is not valid for SNMP v3 requests
                ScopedPdu outPdu = new ScopedPdu(pdu);
                SnmpV3Packet packet = new SnmpV3Packet(outPdu);
                secparams.InitializePacket(packet);
                if (secparams.HasCachedKeys)
                    outPacket = packet.encode(secparams.AuthenticationKey, secparams.PrivacyKey);
                else
                    outPacket = packet.encode();
            }
            else if (agentParameters.Version == SnmpVersion.Ver1)
            {
                AgentParameters param = (AgentParameters)agentParameters;
                if (!param.Valid())
                    throw new SnmpException(SnmpException.InvalidIAgentParameters,"Invalid AgentParameters. Unable to process request.");
                SnmpV1Packet packet = new SnmpV1Packet();
                packet.Pdu.Set(pdu);
                packet.Community.Set(param.Community);
                outPacket = packet.encode();
                _noSourceCheck = param.DisableReplySourceCheck;
            }
            else if (agentParameters.Version == SnmpVersion.Ver2)
            {
                AgentParameters param = (AgentParameters)agentParameters;
                if (!param.Valid())
                    throw new SnmpException(SnmpException.InvalidIAgentParameters, "Invalid AgentParameters. Unable to process request.");
                SnmpV2Packet packet = new SnmpV2Packet();
                packet.Pdu.Set(pdu);
                packet.Community.Set(param.Community);
                _noSourceCheck = param.DisableReplySourceCheck;
                outPacket = packet.encode();
            }
            else
            {
                throw new SnmpInvalidVersionException("Unsupported SNMP version.");
            }

            byte[] inBuffer = base.Request(_address, _port, outPacket, outPacket.Length, _timeout, _retry);

            if (inBuffer == null || inBuffer.Length <= 0)
            {
                return null;
            }
            // verify packet
            if (agentParameters.Version == SnmpVersion.Ver1)
            {
                SnmpV1Packet packet = new SnmpV1Packet();
                AgentParameters param = (AgentParameters)agentParameters;
                packet.decode(inBuffer, inBuffer.Length);
                if (packet.Community != param.Community)
                {
                    // invalid community name received. Ignore the rest of the packet
                    throw new SnmpAuthenticationException("Invalid community name in reply.");
                }
                if (packet.Pdu.RequestId != pdu.RequestId)
                {
                    // invalid request id. unmatched response ignored
                    throw new SnmpException(SnmpException.InvalidRequestId, "Invalid request id in reply.");
                }
                return packet;
            }
            else if (agentParameters.Version == SnmpVersion.Ver2)
            {
                SnmpV2Packet packet = new SnmpV2Packet();
                AgentParameters param = (AgentParameters)agentParameters;
                packet.decode(inBuffer, inBuffer.Length);
                if (packet.Community != param.Community)
                {
                    // invalid community name received. Ignore the rest of the packet
                    throw new SnmpAuthenticationException("Invalid community name in reply.");
                }
                if (packet.Pdu.RequestId != pdu.RequestId)
                {
                    // invalid request id. unmatched response ignored
                    throw new SnmpException(SnmpException.InvalidRequestId, "Invalid request id in reply.");
                }
                return packet;
            }
            else if (agentParameters.Version == SnmpVersion.Ver3)
            {
                SnmpV3Packet packet = new SnmpV3Packet();
                SecureAgentParameters secparams = (SecureAgentParameters)agentParameters;
                secparams.InitializePacket(packet);
                if (secparams.HasCachedKeys)
                    packet.decode(inBuffer, inBuffer.Length, secparams.AuthenticationKey, secparams.PrivacyKey);
                else
                    packet.decode(inBuffer, inBuffer.Length);
                // first check if packet is a discovery response and process it
                if (packet.Pdu.Type == PduType.Report && packet.Pdu.VbCount > 0 && packet.Pdu.VbList[0].Oid.Equals(SnmpConstants.usmStatsUnknownEngineIDs))
                {
                    secparams.UpdateDiscoveryValues(packet);
                    return packet;
                }
                else
                {
                    if (!secparams.ValidateIncomingPacket(packet))
                    {
                        return null;
                    }
                    else
                    {
                        secparams.UpdateDiscoveryValues(packet); // update time, etc. values
                        return packet;
                    }
                }
            }
            return null;
        }
Example #12
0
 /// <summary>
 /// Send SNMP version 2 Trap notification
 /// </summary>
 /// <param name="packet">SNMP v2 Trap packet class</param>
 /// <param name="peer">Manager (receiver) IP address</param>
 /// <param name="port">Manager (receiver) UDP port number</param>
 public void SendV2Trap(SnmpV2Packet packet, IpAddress peer, int port)
 {
     if (packet.Pdu.Type != PduType.V2Trap)
         throw new SnmpInvalidPduTypeException("Invalid Pdu type.");
     byte[] outBuffer = packet.encode();
     _sock.SendTo(outBuffer, new IPEndPoint((IPAddress)peer, port));
 }
Example #13
0
        internal void AsyncResponse(AsyncRequestResult result, IPEndPoint peer, byte[] buffer, int buflen)
        {
            if (result != AsyncRequestResult.NoError)
            {
                _response(result, null);
            }
            else
            {
                if (buffer == null || buffer.Length <= 0 || buflen <= 0)
                {
                    _response(AsyncRequestResult.NoDataReceived, null);
                    return;
                }
                // verify packet
                if (_agentParameters.Version == (int)SnmpVersion.Ver1)
                {
                    SnmpV1Packet packet = new SnmpV1Packet();
                    try
                    {
                        packet.decode(buffer, buflen);
                    }
                    catch (Exception ex)
                    {
                        ex.GetType();
                        // Console.WriteLine("Exception while decoding SNMP packet: " + ex.ToString());
                        _response(AsyncRequestResult.DecodeError, packet);
                        return;
                    }
                    _response(AsyncRequestResult.NoError, packet);
                    return;
                }
                else if (_agentParameters.Version == SnmpVersion.Ver2)
                {
                    SnmpV2Packet packet = new SnmpV2Packet();
                    try
                    {
                        packet.decode(buffer, buflen);
                    }
                    catch (Exception ex)
                    {
                        ex.GetType();
                        // Console.WriteLine("Exception while decoding SNMP packet: " + ex.ToString());
                        // MutableByte b = new MutableByte(buffer, buflen);
                        // Console.WriteLine("Buffer length {0}", buflen);
                        // SnmpConstants.DumpHex(b);
                        _response(AsyncRequestResult.DecodeError, packet);
                        return;
                    }

                    _response(AsyncRequestResult.NoError, packet);
                }
                else if (_agentParameters.Version == SnmpVersion.Ver3)
                {
                    SnmpV3Packet          packet    = new SnmpV3Packet();
                    SecureAgentParameters secparams = (SecureAgentParameters)_agentParameters;
                    secparams.InitializePacket(packet);
                    try {
                        if (secparams.HasCachedKeys)
                        {
                            packet.decode(buffer, buflen, secparams.AuthenticationKey, secparams.PrivacyKey);
                        }
                        else
                        {
                            packet.decode(buffer, buflen);
                        }
                    }
                    catch
                    {
                        _response(AsyncRequestResult.DecodeError, packet);
                        return;
                    }
                    if (!secparams.ValidateIncomingPacket(packet))
                    {
                        _response(AsyncRequestResult.AuthenticationError, packet);
                    }
                    else
                    {
                        secparams.UpdateDiscoveryValues(packet);                         // update time, etc. values
                        _response(AsyncRequestResult.NoError, packet);
                    }
                }
            }
        }
Example #14
0
        /// <summary>
        /// Make SNMP request. With this method you can make blocked SNMP version 1, 2 and 3 requests of type GET,
        /// GET-NEXT, GET-BULK, SET and REPORT (request types have to compatible with the SNMP protocol version you
        /// are using).
        ///
        /// This method will pass through any exceptions thrown by parsing classes/methods so see individual packet
        /// classes, ASN.1 type classes, authentication, privacy, etc. classes for exceptions thrown.
        /// </summary>
        /// <param name="pdu">Pdu class (do not pass ScopedPdu)</param>
        /// <param name="agentParameters">Security information for the request. Use <see cref="AgentParameters"/>
        /// for SNMP versions 1 and 2 requests. Use <see cref="SecureAgentParameters"/> for SNMP version 3
        /// requests.</param>
        /// <param name="responseCallback">Callback that receives the result of the async operation.</param>
        /// <returns>True if async request was successfully initiated, otherwise false.</returns>
        public bool RequestAsync(Pdu pdu, IAgentParameters agentParameters, SnmpAsyncResponse responseCallback)
        {
            if (IsBusy)
            {
                return(false);                // class is busy
            }
            _response        = null;
            _response       += responseCallback;
            _agentParameters = agentParameters;
            byte[] outPacket;
            if (agentParameters.Version == SnmpVersion.Ver3)
            {
                SecureAgentParameters secparams = (SecureAgentParameters)agentParameters;
                if (secparams.Authentication != AuthenticationDigests.None && secparams.AuthenticationSecret.Length <= 0)
                {
                    // _response(AsyncRequestResult.AuthenticationError, null);
                    return(false);
                }
                if (secparams.Privacy != PrivacyProtocols.None && secparams.PrivacySecret.Length <= 0)
                {
                    // _response(AsyncRequestResult.PrivacyError, null);
                    return(false);
                }
                _noSourceCheck = false;                 // this option is not valid for SNMP v3 requests
                ScopedPdu outPdu = new ScopedPdu(pdu);
                outPdu.ContextEngineId.Set(secparams.EngineId);
                outPdu.ContextName.Set(secparams.ContextName);
                SnmpV3Packet packet = new SnmpV3Packet(outPdu);
                secparams.InitializePacket(packet);
                try
                {
                    if (secparams.HasCachedKeys)
                    {
                        outPacket = packet.encode(secparams.AuthenticationKey, secparams.PrivacyKey);
                    }
                    else
                    {
                        outPacket = packet.encode();
                    }
                }
                catch (Exception ex)
                {
                    ex.GetType();
                    _response(AsyncRequestResult.EncodeError, packet);
                    return(false);
                }
            }
            else if (agentParameters.Version == (int)SnmpVersion.Ver1)
            {
                AgentParameters param = (AgentParameters)agentParameters;
                _noSourceCheck = param.DisableReplySourceCheck;
                SnmpV1Packet packet = new SnmpV1Packet();
                packet.Pdu.Set(pdu);
                packet.Community.Set(param.Community);
                try
                {
                    outPacket = packet.encode();
                }
                catch (Exception ex)
                {
                    ex.GetType();
                    _response(AsyncRequestResult.EncodeError, packet);
                    return(false);
                }
            }
            else if (agentParameters.Version == SnmpVersion.Ver2)
            {
                AgentParameters param = (AgentParameters)agentParameters;
                _noSourceCheck = param.DisableReplySourceCheck;
                SnmpV2Packet packet = new SnmpV2Packet();
                packet.Pdu.Set(pdu);
                packet.Community.Set(param.Community);
                try
                {
                    outPacket = packet.encode();
                }
                catch (Exception ex)
                {
                    ex.GetType();
                    _response(AsyncRequestResult.EncodeError, packet);
                    return(false);
                }
            }
            else
            {
                throw new SnmpInvalidVersionException("Unsupported SNMP version.");
            }

            if (!base.RequestAsync(_address, _port, outPacket, outPacket.Length, _timeout, _retry, new SnmpAsyncCallback(AsyncResponse)))
            {
                return(false);
            }
            return(true);
        }
Example #15
0
        /// <summary>Make SNMP Request</summary>
        /// <remarks>
        /// Make SNMP request. With this method you can make blocked SNMP version 1, 2 and 3 requests of type GET,
        /// GET-NEXT, GET-BULK, SET and REPORT (request types have to compatible with the SNMP protocol version you
        /// are using).
        ///
        /// This method will pass through any exceptions thrown by parsing classes/methods so see individual packet
        /// classes, ASN.1 type classes, authentication, privacy, etc. classes for exceptions thrown.
        /// </remarks>
        /// <param name="pdu">Pdu class (do not pass ScopedPdu)</param>
        /// <param name="agentParameters">Security information for the request. Use <see cref="AgentParameters"/>
        /// for SNMP versions 1 and 2 requests. Use <see cref="SecureAgentParameters"/> for SNMP version 3
        /// requests.</param>
        /// <returns>Appropriate SNMP packet class for the reply received (<see cref="SnmpV1Packet"/>,
        /// <see cref="SnmpV2Packet"/>, or <see cref="SnmpV3Packet"/>. Null value if there was an error
        /// with the request.</returns>
        /// <exception cref="SnmpAuthenticationException">Thrown on SNMPv3 requests when authentication password
        /// is not specified on authNoPriv or authPriv requests in SecureAgentParameters or if incoming packet
        /// authentication check failed.
        ///
        /// With SNMP ver1 and ver2c, authentication check fails when invalid community name is parsed in the reply.</exception>
        /// <exception cref="SnmpPrivacyException">Thrown on SNMPv3 requests when privacy password is not
        /// specified in SecureAgentParameters on authPriv requests.</exception>
        /// <exception cref="SnmpException">Thrown in following cases:
        ///
        /// * IAgentParameters.Valid() returned false. SnmpException.ErrorCode is set to SnmpException.InvalidIAgentParameters
        /// * No data received on request. SnmpException.ErrorCode is set to SnmpException.NoDataReceived
        /// * Invalid RequestId in reply. SnmpException.ErrorCode is set to SnmpException.InvalidRequestId
        /// </exception>
        public SnmpPacket Request(Pdu pdu, IAgentParameters agentParameters)
        {
            byte[] outPacket;
            if (agentParameters.Version == SnmpVersion.Ver3)
            {
                SecureAgentParameters secparams = (SecureAgentParameters)agentParameters;
                if (secparams.Authentication != AuthenticationDigests.None && secparams.AuthenticationSecret.Length <= 0)
                {
                    throw new SnmpAuthenticationException("Authentication password not specified.");
                }
                if (secparams.Privacy != PrivacyProtocols.None && secparams.PrivacySecret.Length <= 0)
                {
                    throw new SnmpPrivacyException("Privacy password not specified.");
                }
                _noSourceCheck = false;                 // this option is not valid for SNMP v3 requests
                ScopedPdu    outPdu = new ScopedPdu(pdu);
                SnmpV3Packet packet = new SnmpV3Packet(outPdu);
                secparams.InitializePacket(packet);
                if (secparams.HasCachedKeys)
                {
                    outPacket = packet.encode(secparams.AuthenticationKey, secparams.PrivacyKey);
                }
                else
                {
                    outPacket = packet.encode();
                }
            }
            else if (agentParameters.Version == SnmpVersion.Ver1)
            {
                AgentParameters param = (AgentParameters)agentParameters;
                if (!param.Valid())
                {
                    throw new SnmpException(SnmpException.InvalidIAgentParameters, "Invalid AgentParameters. Unable to process request.");
                }
                SnmpV1Packet packet = new SnmpV1Packet();
                packet.Pdu.Set(pdu);
                packet.Community.Set(param.Community);
                outPacket      = packet.encode();
                _noSourceCheck = param.DisableReplySourceCheck;
            }
            else if (agentParameters.Version == SnmpVersion.Ver2)
            {
                AgentParameters param = (AgentParameters)agentParameters;
                if (!param.Valid())
                {
                    throw new SnmpException(SnmpException.InvalidIAgentParameters, "Invalid AgentParameters. Unable to process request.");
                }
                SnmpV2Packet packet = new SnmpV2Packet();
                packet.Pdu.Set(pdu);
                packet.Community.Set(param.Community);
                _noSourceCheck = param.DisableReplySourceCheck;
                outPacket      = packet.encode();
            }
            else
            {
                throw new SnmpInvalidVersionException("Unsupported SNMP version.");
            }

            byte[] inBuffer = base.Request(_address, _port, outPacket, outPacket.Length, _timeout, _retry);

            if (inBuffer == null || inBuffer.Length <= 0)
            {
                throw new SnmpException(SnmpException.NoDataReceived, "No data received on request.");
            }
            // verify packet
            if (agentParameters.Version == SnmpVersion.Ver1)
            {
                SnmpV1Packet    packet = new SnmpV1Packet();
                AgentParameters param  = (AgentParameters)agentParameters;
                packet.decode(inBuffer, inBuffer.Length);
                if (packet.Community != param.Community)
                {
                    // invalid community name received. Ignore the rest of the packet
                    throw new SnmpAuthenticationException("Invalid community name in reply.");
                }
                if (packet.Pdu.RequestId != pdu.RequestId)
                {
                    // invalid request id. unmatched response ignored
                    throw new SnmpException(SnmpException.InvalidRequestId, "Invalid request id in reply.");
                }
                return(packet);
            }
            else if (agentParameters.Version == SnmpVersion.Ver2)
            {
                SnmpV2Packet    packet = new SnmpV2Packet();
                AgentParameters param  = (AgentParameters)agentParameters;
                packet.decode(inBuffer, inBuffer.Length);
                if (packet.Community != param.Community)
                {
                    // invalid community name received. Ignore the rest of the packet
                    throw new SnmpAuthenticationException("Invalid community name in reply.");
                }
                if (packet.Pdu.RequestId != pdu.RequestId)
                {
                    // invalid request id. unmatched response ignored
                    throw new SnmpException(SnmpException.InvalidRequestId, "Invalid request id in reply.");
                }
                return(packet);
            }
            else if (agentParameters.Version == SnmpVersion.Ver3)
            {
                SnmpV3Packet          packet    = new SnmpV3Packet();
                SecureAgentParameters secparams = (SecureAgentParameters)agentParameters;
                secparams.InitializePacket(packet);
                if (secparams.HasCachedKeys)
                {
                    packet.decode(inBuffer, inBuffer.Length, secparams.AuthenticationKey, secparams.PrivacyKey);
                }
                else
                {
                    packet.decode(inBuffer, inBuffer.Length);
                }
                // first check if packet is a discovery response and process it
                if (packet.Pdu.Type == PduType.Report && packet.Pdu.VbCount > 0 && packet.Pdu.VbList[0].Oid.Equals(SnmpConstants.usmStatsUnknownEngineIDs))
                {
                    secparams.UpdateDiscoveryValues(packet);
                    return(packet);
                }
                else
                {
                    if (!secparams.ValidateIncomingPacket(packet))
                    {
                        return(null);
                    }
                    else
                    {
                        secparams.UpdateDiscoveryValues(packet);                         // update time, etc. values
                        return(packet);
                    }
                }
            }
            return(null);
        }
Example #16
0
        private string getTrapByOID(SnmpV2Packet packet,string oidPattern, string textPattern)
        {
            //MessageBox.Show(packet.Pdu.ToString());
                foreach (Vb trapOidObj in  packet.Pdu.VbList)
                {

                    //MessageBox.Show("trap: " + trapOidObj.Oid.ToString() + " pattern:" + oidPattern);
                    if (trapOidObj.Oid.ToString().Contains(oidPattern))
                    {
                        string trapString = trapOidObj.Value.ToString();
                        string customData = parseDataByContent(trapString,textPattern);

                        //MessageBox.Show(trapString + "." + customData);

                        //если мы нашли специальное значение внутри - то вернем его
                        if (customData != "")
                        {
                            return customData;
                        }
                        else{
                            //иначе вернем все данные трапа
                            return trapString;
                        }

                    }
                }

                return "";
        }
Example #17
0
        private void recv(IAsyncResult res)
        {
            IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
            byte[] received = Client.EndReceive(res, ref RemoteIpEndPoint);

            //Process codes

               // MessageBox.Show(Encoding.UTF8.GetString(received));

            SnmpV2Packet pkt = new SnmpV2Packet();
            pkt.decode(received, received.Length);

            _debug("Получен TRAP с адреса " + RemoteIpEndPoint.ToString());

            //NotifyIcon notifyObj = new NotifyIcon();

            //notifyObj.ShowBalloon(Convert.ToUInt32(ToolTipIcon.Info) ,"Сообщение", "Я свернулась:)",5000 );

            string trapData = "";

            foreach (Vb v in pkt.Pdu.VbList)
            {
                trapData = String.Concat(trapData, "**** " +
                   v.Oid.ToString() + " " +
                   SnmpConstants.GetTypeName(v.Value.Type) + " " +
                   v.Value.ToString());
            }

            Trap trp = new Trap(RemoteIpEndPoint.ToString(), pkt);

            if (checkForExcludes(trp))
            {

                //через анонимный делегат отправим данные трапа на грид, чтобы не подвисал интерфейс, т.к. шлем из другого потока
                this.Invoke((MethodInvoker)delegate
                {

                    //выведем нотификацию
                    taskbarNotifier.Show("", "Получен трап с адреса " + RemoteIpEndPoint.ToString() + Environment.NewLine +
                                            "Community:" + trp.tCommunity, 300, 3000, 300);

                    tList.addTrap(trp);
                    addTrapToGrid(trp); // runs on UI thread

                });

                tList.saveToFile();

            }
            Client.BeginReceive(new AsyncCallback(recv), null);
        }
Example #18
0
        private void button1_Click(object sender, EventArgs e)
        {
            // Construct a socket and bind it to the trap manager port 162
            Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 162);
            EndPoint ep = (EndPoint)ipep;
            socket.Bind(ep);
            // Disable timeout processing. Just block until packet is received
            socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 0);
            bool run = true;
            int inlen = -1;
            while (run)
            {
                Application.DoEvents();
                Thread.Sleep(100);
                byte[] indata = new byte[16 * 1024];
                // 16KB receive buffer int inlen = 0;
                IPEndPoint peer = new IPEndPoint(IPAddress.Any, 0);
                EndPoint inep = (EndPoint)peer;
                try
                {

                    inlen = socket.ReceiveFrom(indata, ref inep);

                }
                catch (Exception ex)
                {
                    Console.WriteLine("Exception {0}", ex.Message);
                    inlen = -1;
                }
                if (inlen > 0)
                {
                    // Check protocol version int
                    int ver = SnmpPacket.GetProtocolVersion(indata, inlen);
                    if (ver == (int)SnmpVersion.Ver1)
                    {
                        // Parse SNMP Version 1 TRAP packet
                        SnmpV1TrapPacket pkt = new SnmpV1TrapPacket();
                        pkt.decode(indata, inlen);
                        Console.WriteLine("** SNMP Version 1 TRAP received from {0}:", inep.ToString());
                        Console.WriteLine("*** Trap generic: {0}", pkt.Pdu.Generic);
                        Console.WriteLine("*** Trap specific: {0}", pkt.Pdu.Specific);
                        Console.WriteLine("*** Agent address: {0}", pkt.Pdu.AgentAddress.ToString());
                        Console.WriteLine("*** Timestamp: {0}", pkt.Pdu.TimeStamp.ToString());
                        Console.WriteLine("*** VarBind count: {0}", pkt.Pdu.VbList.Count);
                        Console.WriteLine("*** VarBind content:");
                        foreach (Vb v in pkt.Pdu.VbList)
                        {
                            Console.WriteLine("**** {0} {1}: {2}", v.Oid.ToString(), SnmpConstants.GetTypeName(v.Value.Type), v.Value.ToString());
                            textBox1.Text += "\n" + v.Oid.ToString() + "|" + SnmpConstants.GetTypeName(v.Value.Type) + "|" + v.Value.ToString();
                        }
                        Console.WriteLine("** End of SNMP Version 1 TRAP data.");
                    }
                    else
                    {
                        // Parse SNMP Version 2 TRAP packet
                        SnmpV2Packet pkt = new SnmpV2Packet();
                        pkt.decode(indata, inlen);
                        Console.WriteLine("** SNMP Version 2 TRAP received from {0}:", inep.ToString());
                        if ((SnmpSharpNet.PduType)pkt.Pdu.Type != PduType.V2Trap)
                        {
                            Console.WriteLine("*** NOT an SNMPv2 trap ****");
                        }
                        else
                        {
                            Console.WriteLine("*** Community: {0}", pkt.Community.ToString());
                            Console.WriteLine("*** VarBind count: {0}", pkt.Pdu.VbList.Count);
                            Console.WriteLine("*** VarBind content:");
                            foreach (Vb v in pkt.Pdu.VbList)
                            {
                                Console.WriteLine("**** {0} {1}: {2}",
                                   v.Oid.ToString(), SnmpConstants.GetTypeName(v.Value.Type), v.Value.ToString());
                            }
                            Console.WriteLine("** End of SNMP Version 2 TRAP data.");
                        }
                    }
                }
                else
                {
                    if (inlen == 0)
                        Console.WriteLine("Zero length packet received.");
                }
            }
        }
Example #19
0
 /// <summary>
 /// Build SNMP RESPONSE packet for the received INFORM packet.
 /// </summary>
 /// <returns>SNMP version 2 packet containing RESPONSE to the INFORM packet contained in the class instance.</returns>
 public SnmpV2Packet BuildInformResponse()
 {
     return(SnmpV2Packet.BuildInformResponse(this));
 }
Example #20
0
        /// <summary>
        /// Make SNMP request. With this method you can make blocked SNMP version 1, 2 and 3 requests of type GET,
        /// GET-NEXT, GET-BULK, SET and REPORT (request types have to compatible with the SNMP protocol version you
        /// are using).
        /// 
        /// This method will pass through any exceptions thrown by parsing classes/methods so see individual packet
        /// classes, ASN.1 type classes, authentication, privacy, etc. classes for exceptions thrown.
        /// </summary>
        /// <param name="pdu">Pdu class (do not pass ScopedPdu)</param>
        /// <param name="agentParameters">Security information for the request. Use <see cref="AgentParameters"/>
        /// for SNMP versions 1 and 2 requests. Use <see cref="SecureAgentParameters"/> for SNMP version 3
        /// requests.</param>
        /// <param name="responseCallback">Callback that receives the result of the async operation.</param>
        /// <returns>True if async request was successfully initiated, otherwise false.</returns>
        public bool RequestAsync(Pdu pdu, IAgentParameters agentParameters, SnmpAsyncResponse responseCallback)
        {
            if (IsBusy)
            {
                return false; // class is busy
            }
            _response = null;
            _response += responseCallback;
            _agentParameters = agentParameters;
            byte[] outPacket;
            if (agentParameters.Version == SnmpVersion.Ver3)
            {
                SecureAgentParameters secparams = (SecureAgentParameters)agentParameters;
                if (secparams.Authentication != AuthenticationDigests.None && secparams.AuthenticationSecret.Length <= 0)
                {
                    // _response(AsyncRequestResult.AuthenticationError, null);
                    return false;
                }
                if (secparams.Privacy != PrivacyProtocols.None && secparams.PrivacySecret.Length <= 0)
                {
                    // _response(AsyncRequestResult.PrivacyError, null);
                    return false;
                }
                _noSourceCheck = false; // this option is not valid for SNMP v3 requests
                ScopedPdu outPdu = new ScopedPdu(pdu);
                outPdu.ContextEngineId.Set(secparams.EngineId);
                outPdu.ContextName.Set(secparams.ContextName);
                SnmpV3Packet packet = new SnmpV3Packet(outPdu);
                secparams.InitializePacket(packet);
                try
                {
                    if (secparams.HasCachedKeys)
                        outPacket = packet.encode(secparams.AuthenticationKey, secparams.PrivacyKey);
                    else
                        outPacket = packet.encode();
                }
                catch( Exception ex )
                {
                    ex.GetType();
                    _response(AsyncRequestResult.EncodeError, packet);
                    return false;
                }
            }
            else if (agentParameters.Version == (int)SnmpVersion.Ver1)
            {
                AgentParameters param = (AgentParameters)agentParameters;
                _noSourceCheck = param.DisableReplySourceCheck;
                SnmpV1Packet packet = new SnmpV1Packet();
                packet.Pdu.Set(pdu);
                packet.Community.Set(param.Community);
                try
                {
                    outPacket = packet.encode();
                }
                catch( Exception ex)
                {
                    ex.GetType();
                    _response(AsyncRequestResult.EncodeError, packet);
                    return false;
                }
            }
            else if (agentParameters.Version == SnmpVersion.Ver2)
            {
                AgentParameters param = (AgentParameters)agentParameters;
                _noSourceCheck = param.DisableReplySourceCheck;
                SnmpV2Packet packet = new SnmpV2Packet();
                packet.Pdu.Set(pdu);
                packet.Community.Set(param.Community);
                try
                {
                    outPacket = packet.encode();
                }
                catch( Exception ex )
                {
                    ex.GetType();
                    _response(AsyncRequestResult.EncodeError, packet);
                    return false;
                }
            }
            else
            {
                throw new SnmpInvalidVersionException("Unsupported SNMP version.");
            }

            if( ! base.RequestAsync(_address, _port, outPacket, outPacket.Length, _timeout, _retry, new SnmpAsyncCallback(AsyncResponse) ) ) {
                return false;
            }
            return true;
        }
Example #21
0
        public void zlapPulapke()
        {
            /*! 
		     *Kod pochodzi ze strony http://www.snmpsharpnet.com/?page_id=117
             */
            Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 162);
            EndPoint ep = (EndPoint)ipep;
            socket.Bind(ep);
            // Disable timeout processing. Just block until packet is received 
            socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 0);
            bool run = true;
            int inlen = -1;
            while (run)
            {
                byte[] indata = new byte[16 * 1024];
                // 16KB receive buffer int inlen = 0;
                IPEndPoint peer = new IPEndPoint(IPAddress.Any, 0);
                EndPoint inep = (EndPoint)peer;
                try
                {
                    inlen = socket.ReceiveFrom(indata, ref inep);
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Exception {0}", ex.Message);
                    inlen = -1;
                }
                if (inlen > 0)
                {
                    Console.WriteLine("TAK");

                    listaWierszyZeZlapanejPualpki.Clear();
                    // Check protocol version int 
                    int ver = SnmpPacket.GetProtocolVersion(indata, inlen);
                    if (ver == (int)SnmpVersion.Ver1)
                    {
                        // Parse SNMP Version 1 TRAP packet 
                        SnmpV1TrapPacket pkt = new SnmpV1TrapPacket();
                        pkt.decode(indata, inlen);
                        listaWierszyZeZlapanejPualpki.Add("** SNMP Version 1 TRAP otrzymane od " + inep.ToString());
                        listaWierszyZeZlapanejPualpki.Add("*** Trap generic: " + pkt.Pdu.Generic);
                        listaWierszyZeZlapanejPualpki.Add("*** Trap specific: " + pkt.Pdu.Specific);
                        listaWierszyZeZlapanejPualpki.Add("*** Agent address: " + pkt.Pdu.AgentAddress.ToString());
                        listaWierszyZeZlapanejPualpki.Add("*** Timestamp: " + pkt.Pdu.TimeStamp.ToString());
                        listaWierszyZeZlapanejPualpki.Add("*** VarBind count: " + pkt.Pdu.VbList.Count);
                        listaWierszyZeZlapanejPualpki.Add("*** VarBind content:");
                        foreach (Vb v in pkt.Pdu.VbList)
                        {
                            StringBuilder budowaStringa = new StringBuilder();
                            budowaStringa.Append("**** ");
                            budowaStringa.Append(v.Oid.ToString());
                            budowaStringa.Append(" " + SnmpConstants.GetTypeName(v.Value.Type));
                            budowaStringa.Append(": " + v.Value.ToString());
                            listaWierszyZeZlapanejPualpki.Add(budowaStringa.ToString());
                        }
                        listaWierszyZeZlapanejPualpki.Add("** Koniec SNMP Version 1 TRAP data.");
                        flagaWierszyZeZlapanejPulapki = true;
                        //return true;
                    }
                    else {
                        // Parse SNMP Version 2 TRAP packet 
                        SnmpV2Packet pkt = new SnmpV2Packet();
                        pkt.decode(indata, inlen);
                        listaWierszyZeZlapanejPualpki.Clear();
                        listaWierszyZeZlapanejPualpki.Add("** SNMP Version 2 TRAP otrzymane od " + inep.ToString());
                        if ((SnmpSharpNet.PduType)pkt.Pdu.Type != PduType.V2Trap)
                        {
                            listaWierszyZeZlapanejPualpki.Add("*** NOT an SNMPv2 trap ****");
                        }
                        else {
                            listaWierszyZeZlapanejPualpki.Add("*** Community: " + pkt.Community.ToString());
                            listaWierszyZeZlapanejPualpki.Add("*** VarBind count: " + pkt.Pdu.VbList.Count);
                            listaWierszyZeZlapanejPualpki.Add("*** VarBind content:");
                            foreach (Vb v in pkt.Pdu.VbList)
                            {
                                StringBuilder budowaStringa = new StringBuilder();
                                budowaStringa.Append("**** ");
                                budowaStringa.Append(v.Oid.ToString());
                                budowaStringa.Append(" " + SnmpConstants.GetTypeName(v.Value.Type));
                                budowaStringa.Append(": " + v.Value.ToString());
                                listaWierszyZeZlapanejPualpki.Add(budowaStringa.ToString());
                            }
                            listaWierszyZeZlapanejPualpki.Add("** Koniec SNMP Version 2 TRAP data.");
                        }
                        flagaWierszyZeZlapanejPulapki = true;
                        //return true;
                    }
                }
                else {
                    if (inlen == 0)
                    {
                        listaWierszyZeZlapanejPualpki.Clear();
                        listaWierszyZeZlapanejPualpki.Add("Przechwycono pusty pakiet");
                        flagaWierszyZeZlapanejPulapki = true;
                        //return true;
                    }
                }
            }
            //return false;
        }
Example #22
0
        /// <summary>
        /// Construct and send SNMP v2 Trap
        /// </summary>
        /// <param name="receiver">Trap receiver IP address</param>
        /// <param name="receiverPort">Trap receiver UDP port number</param>
        /// <param name="community">SNMP community name</param>
        /// <param name="senderUpTime">Sender sysUpTime</param>
        /// <param name="trapObjectID">Trap ObjectID</param>
        /// <param name="varList">Variable binding list</param>
        public void SendV2Trap(IpAddress receiver, int receiverPort, string community, UInt32 senderUpTime,
			Oid trapObjectID, VbCollection varList)
        {
            SnmpV2Packet packet = new SnmpV2Packet(community);
            packet.Pdu.Type = PduType.V2Trap;
            packet.Pdu.TrapObjectID = trapObjectID;
            packet.Pdu.TrapSysUpTime.Value = senderUpTime;
            packet.Pdu.SetVbList(varList);
            SendV2Trap(packet, receiver, receiverPort);
        }
Example #23
0
        private static async Task <bool> WalkGetBulkAsync(IPAddress agent, string community, string oid, Func <Vb, bool> handleValue)
        {
            OctetString communityString = new OctetString(community);

            // Define agent parameters class
            AgentParameters param = new AgentParameters(communityString);

            // Set SNMP version to 2 (GET-BULK only works with SNMP ver 2 and 3)
            param.Version = SnmpVersion.Ver2;

            // Construct target
            UdpTarget target = new UdpTarget(agent, 161, 2000, 1);

            // Define Oid that is the root of the MIB
            //  tree you wish to retrieve
            Oid rootOid = new Oid(oid); // ifDescr

            // This Oid represents last Oid returned by
            //  the SNMP agent
            Oid lastOid = (Oid)rootOid.Clone();

            // Pdu class used for all requests
            Pdu pdu = new Pdu(PduType.GetBulk)
            {
                // In this example, set NonRepeaters value to 0
                NonRepeaters = 0,
                // MaxRepetitions tells the agent how many Oid/Value pairs to return
                // in the response.
                MaxRepetitions = 5
            };

            // Loop through results
            while (lastOid != null)
            {
                // When Pdu class is first constructed, RequestId is set to 0
                // and during encoding id will be set to the random value
                // for subsequent requests, id will be set to a value that
                // needs to be incremented to have unique request ids for each
                // packet
                if (pdu.RequestId != 0)
                {
                    pdu.RequestId += 1;
                }
                // Clear Oids from the Pdu class.
                pdu.VbList.Clear();
                // Initialize request PDU with the last retrieved Oid
                pdu.VbList.Add(lastOid);
                // Make SNMP request
                //var result = (SnmpV1Packet)target.Request(pdu, param);
                SnmpV2Packet result = (SnmpV2Packet)(await target.RequestAsync(pdu, param));

                // You should catch exceptions in the Request if using in real application.

                // If result is null then agent didn't reply or we couldn't parse the reply.
                if (result != null)
                {
                    // ErrorStatus other then 0 is an error returned by
                    // the Agent - see SnmpConstants for error definitions
                    if (result.Pdu.ErrorStatus != 0)
                    {
                        // agent reported an error with the request
                        //System.Diagnostics.Debug.WriteLine("Error in SNMP reply. Error {0} index {1}",
                        //    result.Pdu.ErrorStatus,
                        //    result.Pdu.ErrorIndex);
                        lastOid = null;
                        break;
                    }
                    else
                    {
                        // Walk through returned variable bindings
                        foreach (Vb v in result.Pdu.VbList)
                        {
                            // Check that retrieved Oid is "child" of the root OID
                            if (rootOid.IsRootOf(v.Oid))
                            {
                                //System.Diagnostics.Debug.WriteLine("{0} ({1}): {2}",
                                //    v.Oid.ToString(),
                                //    SnmpConstants.GetTypeName(v.Value.Type),
                                //    v.Value.ToString());

                                handleValue(v);

                                if (v.Value.Type == SnmpConstants.SMI_ENDOFMIBVIEW)
                                {
                                    lastOid = null;
                                }
                                else
                                {
                                    lastOid = v.Oid;
                                }
                            }
                            else
                            {
                                // we have reached the end of the requested
                                // MIB tree. Set lastOid to null and exit loop
                                lastOid = null;
                            }
                        }
                    }
                }
                else
                {
                    //System.Diagnostics.Debug.WriteLine("No response received from SNMP agent.");
                }
            }
            target.Close();
            return(true);
        }
Example #24
0
        /// <summary>
        /// Build SNMP RESPONSE packet for the INFORM packet class.
        /// </summary>
        /// <param name="informPacket">SNMP INFORM packet</param>
        /// <returns>SNMP version 2 packet containing RESPONSE to the INFORM packet contained in the parameter.</returns>
        /// <exception cref="SnmpInvalidPduTypeException">Parameter is not an INFORM SNMP version 2 packet class</exception>
        /// <exception cref="SnmpInvalidVersionException">Parameter is not a SNMP version 2 packet</exception>
        public static SnmpV2Packet BuildInformResponse(SnmpV2Packet informPacket)
        {
            if (informPacket.Version != SnmpVersion.Ver2)
                throw new SnmpInvalidVersionException("INFORM packet can only be parsed from an SNMP version 2 packet.");
            if (informPacket.Pdu.Type != PduType.Inform)
                throw new SnmpInvalidPduTypeException("Inform response can only be built for INFORM packets.");

            SnmpV2Packet response = new SnmpV2Packet(informPacket.Community.ToString());
            response.Pdu.Type = PduType.Response;
            response.Pdu.TrapObjectID.Set(informPacket.Pdu.TrapObjectID);
            response.Pdu.TrapSysUpTime.Value = informPacket.Pdu.TrapSysUpTime.Value;
            foreach (Vb v in informPacket.Pdu.VbList)
            {
                response.Pdu.VbList.Add(v.Oid, v.Value);
            }
            response.Pdu.RequestId = informPacket.Pdu.RequestId;

            return response;
        }