Exemplo n.º 1
0
        public async Task <Variable?> GetV2Async(IPAddress ip, string oid, string community, int retries, int port, TimeSpan timeout)
        {
            if (ip == null)
            {
                throw new ArgumentNullException(nameof(ip));
            }

            if (string.IsNullOrWhiteSpace(oid))
            {
                throw new ArgumentNullException(nameof(oid));
            }

            if (!Regex.IsMatch(oid, @"^(([0-9]+)\.)+[0-9]+$"))
            {
                throw new ArgumentException(oid, nameof(oid));
            }

            if (port <= 0)
            {
                throw new ArgumentOutOfRangeException(nameof(port), port.ToString());
            }

            if (retries <= 0)
            {
                throw new ArgumentOutOfRangeException(nameof(retries), retries.ToString());
            }

            if (timeout <= TimeSpan.Zero)
            {
                throw new ArgumentOutOfRangeException(nameof(timeout), timeout.ToString());
            }

            var startDate   = DateTime.Now;
            var snmpType    = "GET";
            var snmpVersion = "2c";

            var attempt = 0;
            IEnumerable <Variable> result = new List <Variable>();

            while (attempt < retries)
            {
                try
                {
                    result = await MyMessenger.GetAsync(VersionCode.V2,
                                                        new IPEndPoint(ip, port),
                                                        new OctetString(community),
                                                        new List <Variable> {
                        new Variable(new ObjectIdentifier(oid))
                    },
                                                        timeout
                                                        ).ConfigureAwait(false);

                    break;
                }
                catch (Exception ex) when(ex is SnmpException || ex is SocketException || ex is OperationCanceledException)
                {
                    await _SnmpLog.LogTransactionAsync(startDate, ip.ToString(), oid, community, snmpType, snmpVersion, ex.GetType().ToString(), ex.Message).ConfigureAwait(false);

                    ++attempt;
                    if (attempt >= retries)
                    {
                        throw;
                    }
                }
            }

            var type = string.Empty;
            var data = string.Empty;

            foreach (var res in result)
            {
                type += res.Data.TypeCode;
                data += res.Data.ToString();
            }

            await _SnmpLog.LogTransactionAsync(startDate, ip.ToString(), oid, community, snmpType, snmpVersion, type, data).ConfigureAwait(false);

            return(result.FirstOrDefault());
        }