示例#1
0
        private void loadDataResponse()
        {
            this.miThreadState = 1;
            while (this.miThreadState != 0)
            {
                try
                {
                    Dictionary <Oid, AsnType> dicOID = (Dictionary <Oid, AsnType>) this.mgResponseQueue.Dequeue();
                    if (dicOID != null)
                    {
                        foreach (Oid oid in dicOID.Keys)
                        {
                            AsnType asnType = dicOID[oid];

                            appendRowSNMP(dgvSNMPListValue, new object[]
                            {
                                this.dgvSNMPListValue.Rows.Count + 1,
                                oid.ToString(),
                                asnType.ToString(),
                            });
                        }
                    }
                }
                catch (Exception exp)
                {
                    Console.WriteLine(exp.Message);
                }
                Thread.Sleep(200);
            }
        }
示例#2
0
 public static TimeSpan GetTimeSpan(AsnType obj, TimeSpan defaultValue)
 {
     if (obj is TimeTicks tt)
     {
         return((TimeSpan)tt);
     }
     return(defaultValue);
 }
示例#3
0
 public static int GetInteger(AsnType obj, int defaultValue)
 {
     if (obj.Type == AsnType.INTEGER)
     {
         return(((Integer32)obj).Value);
     }
     return(defaultValue);
 }
示例#4
0
        /// <summary>
        /// Convert an AsnType value into an integer.
        /// </summary>
        /// <param name="value">The AsnType value to be converted.</param>
        /// <returns>An integer representation of <paramref name="value"/>, otherwise '-2' indicating 'unknown'.</returns>
        public static int ToInt(this AsnType value)
        {
            int result;

            //Convert value to a string
            //Return the parsed integer if the string can be parsed as an integer, otherwise -2 (reasons above)
            return(int.TryParse(value.ToString(), out result) ? result : -2);
        }
示例#5
0
 public static uint GetUnsignedInteger(AsnType obj, uint defaultValue)
 {
     if (obj is Counter32 c)
     {
         return(c.Value);
     }
     return(defaultValue);
 }
示例#6
0
        private static AsnType CreateOctetString(AsnType value)
        {
            if (IsEmpty(value))
            {
                return(new AsnType(0x04, 0x00));
            }

            return(new AsnType(0x04, value.GetBytes()));
        }
示例#7
0
        private static bool IsEmpty(AsnType value)
        {
            if (null == value)
            {
                return(true);
            }

            return(false);
        }
示例#8
0
        private static AsnType CreateBitString(AsnType value)
        {
            if (IsEmpty(value))
            {
                return(new AsnType(0x03, EMPTY));
            }

            return(CreateBitString(value.GetBytes(), 0x00));
        }
    private byte[] PublicKeyToX509(RSAParameters publicKey)
    {
        AsnType oid         = AsnType.CreateOid("1.2.840.113549.1.1.1");
        AsnType algorithmID = AsnType.CreateSequence(new AsnType[] { oid, AsnType.CreateNull() });

        AsnType n             = AsnType.CreateIntegerPos(publicKey.Modulus);
        AsnType e             = AsnType.CreateIntegerPos(publicKey.Exponent);
        AsnType key           = AsnType.CreateBitString(AsnType.CreateSequence(new AsnType[] { n, e }));
        AsnType publicKeyInfo = AsnType.CreateSequence(new AsnType[] { algorithmID, key });

        return(new AsnMessage(publicKeyInfo.GetBytes(), "X.509").GetBytes());
    }
示例#10
0
        /// <summary>
        ///  转化消息,转化时间刻度
        /// </summary>
        /// <param name="asnType"></param>
        /// <returns></returns>
        public static string ConvertTo(AsnType asnType)
        {
            Type type = asnType.GetType();

            if (type.Equals(typeof(TimeTicks)))
            {
                return(((TimeTicks)asnType).Miliseconds.ToString());
            }
            else
            {
                return(ConvertTo(asnType.ToString()).Replace(",", "_"));
            }
        }
示例#11
0
        /// <summary>
        /// SET class value from another Integer32 class cast as <see cref="AsnType"/>.
        /// </summary>
        /// <param name="value">Integer32 class cast as <see cref="AsnType"/></param>
        /// <exception cref="ArgumentException">Argument is not Integer32 type.</exception>
        public void Set(AsnType value)
        {
            Integer32 val = value as Integer32;

            if (val != null)
            {
                this.value = val.Value;
            }
            else
            {
                throw new ArgumentException("Invalid argument type.");
            }
        }
示例#12
0
        /// <summary>SET class value from another Counter64 class cast as <seealso cref="AsnType"/>.</summary>
        /// <param name="value">Counter64 class cast as <seealso cref="AsnType"/></param>
        /// <exception cref="ArgumentException">Argument is not Counter64 type.</exception>
        public void Set(AsnType value)
        {
            Counter64 val = value as Counter64;

            if (val != null)
            {
                this.value = val.Value;
            }
            else
            {
                throw new ArgumentException("Invalid argument type.");
            }
        }
示例#13
0
        /// <summary>SET class value from another UInteger32 or Integer32 class cast as <seealso cref="AsnType"/>.</summary>
        /// <param name="value">UInteger32 class cast as <seealso cref="AsnType"/></param>
        /// <exception cref="ArgumentNullException">Parameter is null.</exception>
        public void Set(AsnType value)
        {
            if (value == null)
            {
                throw new ArgumentNullException("value", "Parameter is null");
            }

            if (value is UInteger32)
            {
                this.value = ((UInteger32)value).Value;
            }
            else if (value is Integer32)
            {
                this.value = (uint)((Integer32)value).Value;
            }
        }
示例#14
0
        /// <summary>
        /// Converts the
        /// </summary>
        /// <param name="asnType">The <see cref="AsnType" /> to convert.</param>
        /// <param name="converted">Returs the integer representation of the <see cref="AsnType" />.</param>
        /// <returns><c>true</c> if the conversion was successful. Otherwise <c>false</c>.</returns>
        public static bool TryToInt(this AsnType asnType, out int converted)
        {
            if (asnType == null)
            {
                throw new ArgumentNullException(nameof(asnType), "The AsnType to convert to Integer is null");
            }

            converted = int.MinValue;
            if (!int.TryParse(asnType.ToString(), out converted))
            {
                log.Warn($"Cannot convert an ASN Type '{SnmpConstants.GetTypeName(asnType.Type)}' of value '{asnType.ToString()}' to an integer: Value malformatted or out of range");
                return(false);
            }

            return(true);
        }
示例#15
0
        /// <summary>
        /// Converts the
        /// </summary>
        /// <param name="asnType">The <see cref="AsnType" /> to convert.</param>
        /// <returns>Integer representation of the <see cref="AsnType" />.</returns>
        public static int ToInt(this AsnType asnType)
        {
            if (asnType == null)
            {
                throw new ArgumentNullException(nameof(asnType), "The AsnType to convert to Integer is null");
            }

            int convertedValue;

            if (!int.TryParse(asnType.ToString(), out convertedValue))
            {
                throw new HamnetSnmpException($"Cannot convert an ASN Type '{SnmpConstants.GetTypeName(asnType.Type)}' of value '{asnType.ToString()}' to an integer: Value malformatted or out of range");
            }

            return(convertedValue);
        }
示例#16
0
        internal static byte[] PrivateKeyToPKCS8(RSAParameters privateKey)
        {
            AsnType n       = CreateIntegerPos(privateKey.Modulus);
            AsnType e       = CreateIntegerPos(privateKey.Exponent);
            AsnType d       = CreateIntegerPos(privateKey.D);
            AsnType p       = CreateIntegerPos(privateKey.P);
            AsnType q       = CreateIntegerPos(privateKey.Q);
            AsnType dp      = CreateIntegerPos(privateKey.DP);
            AsnType dq      = CreateIntegerPos(privateKey.DQ);
            AsnType iq      = CreateIntegerPos(privateKey.InverseQ);
            AsnType version = CreateInteger(new byte[] { 0 });
            AsnType key     = CreateOctetString(
                CreateSequence(new AsnType[] { version, n, e, d, p, q, dp, dq, iq })
                );

            AsnType algorithmID = CreateSequence(new AsnType[] { CreateOid("1.2.840.113549.1.1.1"), CreateNull() });

            AsnType privateKeyInfo = CreateSequence(new AsnType[] { version, algorithmID, key });

            return(new AsnMessage(privateKeyInfo.GetBytes(), "PKCS#8").GetBytes());
        }
示例#17
0
        /// <summary>
        /// Decode received packet. This method overrides the base implementation that cannot be used with this type of the packet.
        /// </summary>
        /// <param name="buffer">Packet buffer</param>
        /// <param name="length">Buffer length</param>
        public override int Decode(byte[] buffer, int length)
        {
            int         offset = 0;
            MutableByte buf    = new MutableByte(buffer, length);

            offset = base.Decode(buffer, length);


            // parse community
            offset = _snmpCommunity.Decode(buf, offset);

            // look ahead to make sure this is a TRAP packet
            int  tmpOffset  = offset;
            byte tmpAsnType = AsnType.ParseHeader(buffer, ref tmpOffset, out int headerLen);

            if (tmpAsnType != (byte)PduType.Trap)
            {
                throw new SnmpException(string.Format("Invalid SNMP ASN.1 type. Received: {0:x2}", tmpAsnType));
            }
            // decode protocol data unit
            offset = Pdu.Decode(buf, offset);
            return(offset);
        }
示例#18
0
 private void configPduVb(LeafVarBinding leafVb, Pdu pdu)
 {
     System.Collections.Generic.IEnumerator <string> enumerator = leafVb.VarBindings.Keys.GetEnumerator();
     while (enumerator.MoveNext())
     {
         string current = enumerator.Current;
         if (pdu.Type == PduType.Set)
         {
             object  obj   = leafVb.VarBindings[current];
             AsnType value = null;
             if (obj is string)
             {
                 value = new OctetString(System.Convert.ToString(obj));
             }
             else
             {
                 if (obj is int)
                 {
                     value = new Integer32(System.Convert.ToInt32(obj));
                 }
                 else
                 {
                     if (obj is System.Net.IPAddress)
                     {
                         value = new IpAddress(obj as System.Net.IPAddress);
                     }
                 }
             }
             pdu.VbList.Add(new Oid(current), value);
         }
         else
         {
             pdu.VbList.Add(current);
         }
     }
 }
        /// <summary>
        /// Gets the value.
        /// </summary>
        /// <param name="asnValue">The ASN value.</param>
        /// <param name="targetType">Type of the value.</param>
        /// <returns>.NET value compliant</returns>
        private object GetValue(AsnType asnValue, Type targetType)
        {
            object value = asnValue;

            switch (SnmpConstants.GetTypeName(asnValue.Type))
            {
            case "Integer32":
                value = ((Integer32)value).Value;
                break;

            case "Gauge32":
                value = ((Gauge32)value).Value;
                break;

            case "Counter32":
                value = ((Counter32)value).Value;
                break;

            case "TimeTicks":
                value = TimeSpan.FromMilliseconds(((TimeTicks)value).Milliseconds);
                break;

            case "IPAddress":
                value = IPAddress.Parse(((IpAddress)value).ToString());
                break;

            case "OctetString":
                value = asnValue.ToString();
                if (targetType == typeof(DateTime))
                {
                    value = ParseDateAndTime((string)value);
                }
                break;
            }
            return(value);
        }
        private static byte[] Concatenate(AsnType[] values)
        {
            // Nothing in, nothing out
            if (IsEmpty(values))
                return new byte[] { };

            int length = 0;
            foreach (AsnType t in values)
            {
                if (null != t)
                { length += t.GetBytes().Length; }
            }

            byte[] cated = new byte[length];

            int current = 0;
            foreach (AsnType t in values)
            {
                if (null != t)
                {
                    byte[] b = t.GetBytes();

                    Array.Copy(b, 0, cated, current, b.Length);
                    current += b.Length;
                }
            }

            return cated;
        }
示例#21
0
 private static AsnType CreateBitString(AsnType value)
 {
     return(IsEmpty(value) ? new AsnType(0x03, empty) : CreateBitString(value.GetBytes()));
 }
        /// <summary>
        /// <para>An ordered collection zero, one or more types.
        /// Returns the AsnType representing an ASN.1 encoded sequence.</para>
        /// <para>If the AsnType array is null or the array is 0 length,
        /// an empty sequence (length 0) is returned.</para>
        /// </summary>
        /// <param name="values">An AsnType consisting of
        /// the values in the collection to be encoded.</param>
        /// <returns>Returns the AsnType representing an ASN.1
        /// encoded sequence.</returns>
        /// <seealso cref="CreateSet(AsnType)"/>
        /// <seealso cref="CreateSet(AsnType[])"/> 
        /// <seealso cref="CreateSetOf(AsnType)"/>
        /// <seealso cref="CreateSetOf(AsnType[])"/>
        /// <seealso cref="CreateSequence(AsnType)"/>
        /// <seealso cref="CreateSequence(AsnType[])"/>
        /// <seealso cref="CreateSequenceOf(AsnType)"/>
        /// <seealso cref="CreateSequenceOf(AsnType[])"/>
        internal static AsnType CreateSequenceOf(AsnType[] values)
        {
            // From the ASN.1 Mailing List
            if (IsEmpty(values))
            { return new AsnType(0x30, EMPTY); }

            // Sequence: Tag 0x30 (16, Universal, Constructed)
            return new AsnType(0x30, Concatenate(values));
        }
        /// <summary>
        /// <para>An ordered collection of one or more types.
        /// Returns the AsnType representing an ASN.1 encoded sequence.</para>
        /// <para>If the AsnType is null, an
        /// empty sequence (length 0) is returned.</para>
        /// </summary>
        /// <param name="values">An array of AsnType consisting of
        /// the values in the collection to be encoded.</param>
        /// <returns>Returns the AsnType representing an ASN.1
        /// encoded Set.</returns>
        /// <seealso cref="CreateSet(AsnType)"/>
        /// <seealso cref="CreateSet(AsnType[])"/> 
        /// <seealso cref="CreateSetOf(AsnType)"/>
        /// <seealso cref="CreateSetOf(AsnType[])"/>
        /// <seealso cref="CreateSequence(AsnType)"/>
        /// <seealso cref="CreateSequence(AsnType[])"/>
        /// <seealso cref="CreateSequenceOf(AsnType)"/>
        /// <seealso cref="CreateSequenceOf(AsnType[])"/>
        internal static AsnType CreateSequence(AsnType[] values)
        {
            // Should be at least 1...
            Debug.Assert(!IsEmpty(values));

            // One or more required
            if (IsEmpty(values))
            { throw new ArgumentException("A sequence requires at least one value."); }

            // Sequence: Tag 0x30 (16, Universal, Constructed)
            return new AsnType((0x10 | 0x20), Concatenate(values));
        }
        /// <summary>
        /// An ordered sequence of zero, one or more octets. Returns
        /// the byte[] representing an ASN.1 encoded octet string.
        /// If octets is null or length is 0, an empty (0 length)
        /// o ctet string is returned.
        /// </summary>
        /// <param name="values">An AsnType object to be encoded.</param>
        /// <returns>Returns the AsnType representing an ASN.1
        /// encoded octet string.</returns>
        /// <seealso cref="CreateBitString(byte[])"/>
        /// <seealso cref="CreateBitString(byte[], uint)"/>
        /// <seealso cref="CreateBitString(AsnType)"/>
        /// <seealso cref="CreateBitString(String)"/>
        /// <seealso cref="CreateOctetString(byte[])"/>
        /// <seealso cref="CreateOctetString(AsnType)"/>
        /// <seealso cref="CreateOctetString(String)"/>
        internal static AsnType CreateOctetString(AsnType[] values)
        {
            if (IsEmpty(values))
            {
                // Empty octet string
                return new AsnType(0x04, 0x00);
            }

            // OctetString: Tag 0x04 (4, Universal, Primitive)
            return new AsnType(0x04, Concatenate(values));
        }
        /// <summary>
        /// An ordered sequence of zero, one or more octets. Returns
        /// the byte[] representing an ASN.1 encoded octet string.
        /// If octets is null or length is 0, an empty (0 length)
        /// o ctet string is returned.
        /// </summary>
        /// <param name="value">An AsnType object to be encoded.</param>
        /// <returns>Returns the AsnType representing an ASN.1
        /// encoded octet string.</returns>
        /// <seealso cref="CreateBitString(byte[])"/>
        /// <seealso cref="CreateBitString(byte[], uint)"/>
        /// <seealso cref="CreateBitString(AsnType)"/>
        /// <seealso cref="CreateBitString(String)"/>
        /// <seealso cref="CreateOctetString(byte[])"/>
        /// <seealso cref="CreateOctetString(String)"/>
        internal static AsnType CreateOctetString(AsnType value)
        {
            if (IsEmpty(value))
            {
                // Empty octet string
                return new AsnType(0x04, 0x00);
            }

            // OctetString: Tag 0x04 (4, Universal, Primitive)
            return new AsnType(0x04, value.GetBytes());
        }
        /// <summary>
        /// An ordered sequence of zero, one or more bits. Returns
        /// the AsnType representing an ASN.1 encoded bit string.
        /// If value is null, an empty (0 length) bit string is
        /// returned.
        /// </summary>
        /// <param name="values">An AsnType object to be encoded.</param>
        /// <returns>Returns the AsnType representing an ASN.1
        /// encoded bit string.</returns>
        /// <seealso cref="CreateBitString(byte[])"/>
        /// <seealso cref="CreateBitString(byte[], uint)"/>
        /// <seealso cref="CreateBitString(AsnType)"/>
        /// <seealso cref="CreateBitString(String)"/>
        /// <seealso cref="CreateOctetString(byte[])"/>
        /// <seealso cref="CreateOctetString(AsnType)"/>
        /// <seealso cref="CreateOctetString(AsnType[])"/>
        /// <seealso cref="CreateOctetString(String)"/>
        internal static AsnType CreateBitString(AsnType[] values)
        {
            if (IsEmpty(values))
            { return new AsnType(0x03, EMPTY); }

            // BitString: Tag 0x03 (3, Universal, Primitive)
            return CreateBitString(Concatenate(values), 0x00);
        }
        private static bool IsEmpty(AsnType[] values)
        {
            if (null == values || 0 == values.Length)
                return true;

            return false;
        }
        private static bool IsEmpty(AsnType value)
        {
            if (null == value)
            { return true; }

            return false;
        }
示例#29
0
 private static bool IsEmpty(AsnType value) => null == value;
        /// <summary>
        /// An ordered sequence of zero, one or more bits. Returns
        /// the AsnType representing an ASN.1 encoded bit string.
        /// If value is null, an empty (0 length) bit string is
        /// returned.
        /// </summary>
        /// <param name="value">An AsnType object to be encoded.</param>
        /// <returns>Returns the AsnType representing an ASN.1
        /// encoded bit string.</returns>
        /// <seealso cref="CreateBitString(byte[])"/>
        /// <seealso cref="CreateBitString(byte[], uint)"/>
        /// <seealso cref="CreateBitString(AsnType[])"/>
        /// <seealso cref="CreateBitString(String)"/>
        /// <seealso cref="CreateOctetString(byte[])"/>
        /// <seealso cref="CreateOctetString(AsnType)"/>
        /// <seealso cref="CreateOctetString(AsnType[])"/>
        /// <seealso cref="CreateOctetString(String)"/>
        internal static AsnType CreateBitString(AsnType value)
        {
            if (IsEmpty(value))
            { return new AsnType(0x03, EMPTY); }

            // BitString: Tag 0x03 (3, Universal, Primitive)
            return CreateBitString(value.GetBytes(), 0x00);
        }
示例#31
0
        /// <summary>
        /// <para>An ordered collection zero, one or more types.
        /// Returns the AsnType representing an ASN.1 encoded sequence.</para>
        /// <para>If the AsnType value is null,an
        /// empty sequence (length 0) is returned.</para>
        /// </summary>
        /// <param name="value">An AsnType consisting of
        /// a single value to be encoded.</param>
        /// <returns>Returns the AsnType representing an ASN.1
        /// encoded sequence.</returns>
        /// <seealso cref="CreateSet(AsnType)"/>
        /// <seealso cref="CreateSet(AsnType[])"/> 
        /// <seealso cref="CreateSetOf(AsnType)"/>
        /// <seealso cref="CreateSetOf(AsnType[])"/>
        /// <seealso cref="CreateSequence(AsnType)"/>
        /// <seealso cref="CreateSequence(AsnType[])"/>
        /// <seealso cref="CreateSequenceOf(AsnType)"/>
        /// <seealso cref="CreateSequenceOf(AsnType[])"/>
        public static AsnType CreateSequenceOf(AsnType value)
        {
            // From the ASN.1 Mailing List
            if (IsEmpty(value))
            {
                return new AsnType(0x30, Empty);
            }

            // Sequence: Tag 0x30 (16, Universal, Constructed)
            return new AsnType(0x30, value.GetBytes());
        }
示例#32
0
        /// <summary>
        /// <para>An ordered collection of one or more types.
        /// Returns the AsnType representing an ASN.1 encoded sequence.</para>
        /// <para>If the AsnType is null, an empty sequence (length 0)
        /// is returned.</para>
        /// </summary>
        /// <param name="value">An AsnType consisting of
        /// a single value to be encoded.</param>
        /// <returns>Returns the AsnType representing an ASN.1
        /// encoded sequence.</returns>
        /// <seealso cref="CreateSet(AsnType)"/>
        /// <seealso cref="CreateSet(AsnType[])"/> 
        /// <seealso cref="CreateSetOf(AsnType)"/>
        /// <seealso cref="CreateSetOf(AsnType[])"/>
        /// <seealso cref="CreateSequence(AsnType)"/>
        /// <seealso cref="CreateSequence(AsnType[])"/>
        /// <seealso cref="CreateSequenceOf(AsnType)"/>
        /// <seealso cref="CreateSequenceOf(AsnType[])"/>
        public static AsnType CreateSequence(AsnType value)
        {
            // Should be at least 1...
            Debug.Assert(!IsEmpty(value));

            // One or more required
            if (IsEmpty(value))
            {
                throw new ArgumentException("A sequence requires at least one value.");
            }

            // Sequence: Tag 0x30 (16, Universal, Constructed)
            return new AsnType(0x30, value.GetBytes());
        }
        /// <summary>
        /// Feeds the object.
        /// </summary>
        /// <param name="targetInstance">The target instance.</param>
        /// <param name="rootId">The OID root identifier.</param>
        /// <param name="datas">The datas.</param>
        private void FeedObject(object targetInstance, Oid rootId, Dictionary <Oid, AsnType> datas = null)
        {
            bool snmpWalk = false;

            foreach (PropertyInfo property in targetInstance.GetType().GetProperties())
            {
                OIDAttribute propertyAttribute = property.GetCustomAttribute <OIDAttribute>();
                if (propertyAttribute != null)
                {
                    if (datas == null && !snmpWalk)
                    {
                        snmpWalk = true;
                        datas    = this.Client.Walk(this.Version, propertyAttribute.ObjectId.ToString());
                    }
                    if (datas != null && datas.Count > 0)
                    {
                        if (property.PropertyType.IsGenericType && property.PropertyType.GetGenericTypeDefinition() == typeof(Sequence <>))
                        {
                            object obj = property.GetValue(targetInstance);
                            if (obj == null)
                            {
                                obj = Activator.CreateInstance(property.PropertyType);
                                property.SetValue(targetInstance, obj);
                            }
                            FeedSequence(obj, property.PropertyType.GenericTypeArguments[0], propertyAttribute.ObjectId, datas.Where(i => propertyAttribute.ObjectId.IsRootOf(i.Key)).ToDictionary(k => k.Key, v => v.Value));
                        }
                        else if (property.PropertyType.GetCustomAttribute <SnmpObjectAttribute>() != null && property.PropertyType.IsClass)
                        {
                            object obj = property.GetValue(targetInstance);
                            if (obj == null)
                            {
                                obj = Activator.CreateInstance(property.PropertyType);
                                property.SetValue(targetInstance, obj);
                            }
                            FeedObject(obj, propertyAttribute.ObjectId, datas.Where(i => propertyAttribute.ObjectId.IsRootOf(i.Key)).ToDictionary(k => k.Key, v => v.Value));
                        }
                        else
                        {
                            AsnType asnValue = datas.Where(t => propertyAttribute.ObjectId == t.Key || propertyAttribute.ObjectId.IsRootOf(t.Key)).Select(p => p.Value).SingleOrDefault();
                            if (asnValue != null)
                            {
                                property.SetValue(targetInstance, GetValue(asnValue, property.PropertyType));
                            }
                            else if (property.GetCustomAttribute <RequiredAttribute>() != null)
                            {
                                throw new MissingMemberException(property.ReflectedType.Name, property.Name);
                            }
                        }
                    }
                    if (property.GetCustomAttribute <RequiredAttribute>() != null && property.PropertyType.IsClass && property.GetValue(targetInstance) == null)
                    {
                        throw new MissingMemberException(property.ReflectedType.Name, property.Name);
                    }
                }
                if (snmpWalk)
                {
                    snmpWalk = false;
                    datas    = null;
                }
            }
        }
示例#34
0
        /// <summary>
        /// Perform an SNMP Set.
        /// </summary>
        /// <param name="destination">The destination host.</param>
        /// <param name="oid">The OID to set.</param>
        /// <param name="value">The value to set.</param>
        /// <returns>Nothing.</returns>
        public static async Task SnmpSetAsync(IPAddress destination, string community, Oid oid, AsnType value)
        {
            UdpTarget target = new UdpTarget(destination);

            // Create a SET PDU
            Pdu pdu = new Pdu(EPduType.Set);

            pdu.VbList.Add(oid, value);

            // Set Agent security parameters
            AgentParameters aparam = new AgentParameters(ESnmpVersion.Ver2, new OctetString(community));

            // Response packet
            SnmpV2Packet response;

            try
            {
                // Send request and wait for response
                response = await target.RequestAsync(pdu, aparam) as SnmpV2Packet;
            }
            catch (Exception ex)
            {
                // If exception happens, it will be returned here
                Console.WriteLine(string.Format("Request failed with exception: {0}", ex.Message));
                target.Close();
                return;
            }

            // Make sure we received a response
            if (response == null)
            {
                Console.WriteLine("Error in sending SNMP request.");
            }
            else
            {
                // Check if we received an SNMP error from the agent
                if (response.Pdu.ErrorStatus != 0)
                {
                    Console.WriteLine(string.Format("SNMP agent returned ErrorStatus {0} on index {1}", response.Pdu.ErrorStatus, response.Pdu.ErrorIndex));
                }
                else
                {
                    // Everything is ok. Agent will return the new value for the OID we changed
                    Console.WriteLine(string.Format("Agent response {0}: {1}", response.Pdu[0].Oid.ToString(), response.Pdu[0].Value.ToString()));
                }
            }
        }
示例#35
0
        /// <summary>
        /// Executa uma requisição do tipo Set
        /// </summary>
        /// <param name="setValue">Valor a set definido</param>
        public void Send(AsnType setValue)
        {
            using (var target = new UdpTarget(Host.IP, Host.Port, TimeOut, Retries))
            {
                var agentp = new AgentParameters(SnmpVersion.Ver2, new OctetString(Host.Community));

                // Caso necessario, appenda o .0 na requisição
                var oid = new Oid(Object.OID);
                if (oid[oid.Length - 1] != 0)
                {
                    oid.Add(0);
                }

                // Cria pacote de dados
                RequestData = new Pdu(setValue == null ? PduType.Get : PduType.Set);

                // Adiciona dados da requisição
                switch (RequestData.Type)
                {
                case PduType.Get:
                    RequestData.VbList.Add(oid);
                    break;

                case PduType.Set:
                    RequestData.VbList.Add(oid, setValue);
                    break;

                default:
                    throw new InvalidOperationException("unsupported");
                }
                try
                {
                    if (LogRequests)
                    {
                        Logger.Self.Log(this);
                    }
                    Timestamp = DateTime.Now;

                    // Envia requisição
                    ResponsePacket = target.Request(RequestData, agentp) as SnmpV2Packet;

                    // Trata resposta
                    if (ResponsePacket != null && ResponsePacket.Pdu.ErrorStatus == (int)PduErrorStatus.noError)
                    {
                        // TODO: suportar mais de um retorno
                        var item = ResponsePacket.Pdu.VbList[0];

                        ResponseValue = item.Value;
                        if (LogRequests)
                        {
                            Logger.Self.Log(item);
                        }
                    }
                }
                catch (Exception ex)
                {
                    if (LogRequests)
                    {
                        Logger.Self.Log(ex);
                    }
                    throw new SnmpException("Não foi possível realizar a operação");
                }
            }
        }
示例#36
0
 public static Task SnmpSetAsync(IPAddress destination, string community, string oid, AsnType value)
 {
     return(SnmpSetAsync(destination, community, new Oid(oid), value));
 }