Пример #1
0
        private void snmpAgentThread_ReceiveEvent(object sender, ReceiveEventArgs re)
        {
            int version = SnmpPacket.GetProtocolVersion(re.message, re.message.Length);

            if (version == (int)SnmpVersion.Ver2)
            {
                SnmpV2Packet inPacket = new SnmpV2Packet();
                try
                {
                    inPacket.decode(re.message, re.message.Length);
                }
                catch (Exception ex)
                { }
                if (inPacket.Pdu.Type == PduType.Get)
                {
                    foreach (Vb vb in inPacket.Pdu.VbList)
                    {
                        var value = "Sample";
                        Console.WriteLine($"Request received on {re.inEndPoint.Address}:{re.inEndPoint.Port} : {vb.Oid}");
                        Console.WriteLine($"Answering : {vb.Oid} = {value}");
                        SendResponse(vb.Oid, value, re.inEndPoint);
                    }
                }
            }
        }
Пример #2
0
        public void ParseSnmpV2cGet1()
        {
            var packetVersion = SnmpPacket.GetProtocolVersion(V2cPacket1, V2cPacket1.Length);

            Assert.Equal(ESnmpVersion.Ver2, packetVersion);

            var packet = new SnmpV2Packet();

            packet.Decode(V2cPacket1, V2cPacket1.Length);

            Assert.Equal("CISCO", packet.Community.ToString());

            Assert.False(packet.IsRequest);
            Assert.True(packet.IsResponse);

            Assert.Equal(2029159714, packet.Pdu.RequestId);
            Assert.Equal(EPduErrorStatus.NoError, packet.Pdu.ErrorStatus);
            Assert.Equal(0, packet.Pdu.ErrorIndex);

            Assert.Equal(1, packet.Pdu.VbCount);

            var vb = packet.Pdu.GetVb(0);

            Assert.NotNull(vb);

            Assert.Equal(new Oid("1.0.8802.1.1.1.1.2.1.1.6.3"), vb.Oid);
            Assert.Equal(3, (vb.Value as Integer32).Value);
        }
Пример #3
0
        public void ParseSnmpGet1()
        {
            var packetVersion = SnmpPacket.GetProtocolVersion(Packet1, Packet1.Length);

            Assert.Equal(ESnmpVersion.Ver1, packetVersion);

            var packet = new SnmpV1Packet();

            packet.Decode(Packet1, Packet1.Length);

            Assert.Equal("public", packet.Community.ToString());

            Assert.True(packet.IsRequest);
            Assert.False(packet.IsResponse);

            Assert.Equal(38, packet.Pdu.RequestId);
            Assert.Equal(EPduErrorStatus.NoError, packet.Pdu.ErrorStatus);
            Assert.Equal(0, packet.Pdu.ErrorIndex);

            Assert.Equal(1, packet.Pdu.VbCount);

            var vb = packet.Pdu.GetVb(0);

            Assert.NotNull(vb);

            Assert.Equal(new Oid("1.3.6.1.2.1.1.2.0"), vb.Oid);
        }
Пример #4
0
        public void ParseSnmpGet7()
        {
            var packetVersion = SnmpPacket.GetProtocolVersion(Packet7, Packet7.Length);

            Assert.Equal(ESnmpVersion.Ver1, packetVersion);

            var packet = new SnmpV1Packet();

            packet.Decode(Packet7, Packet7.Length);

            Assert.Equal("public", packet.Community.ToString());

            Assert.True(packet.IsRequest);
            Assert.False(packet.IsResponse);

            Assert.Equal(41, packet.Pdu.RequestId);
            Assert.Equal(EPduErrorStatus.NoError, packet.Pdu.ErrorStatus);
            Assert.Equal(0, packet.Pdu.ErrorIndex);

            Assert.Equal(3, packet.Pdu.VbCount);

            var vb = packet.Pdu.GetVb(0);

            Assert.NotNull(vb);
            Assert.Equal(new Oid("1.3.6.1.4.1.253.8.64.4.2.1.7.10.14130104"), vb.Oid);

            vb = packet.Pdu.GetVb(1);
            Assert.NotNull(vb);
            Assert.Equal(new Oid("1.3.6.1.4.1.253.8.64.4.2.1.7.10.14130102"), vb.Oid);

            vb = packet.Pdu.GetVb(2);
            Assert.NotNull(vb);
            Assert.Equal(new Oid("1.3.6.1.4.1.253.8.64.4.2.1.5.10.14130400"), vb.Oid);
        }
Пример #5
0
        public void ParseSnmResponse2()
        {
            var packetVersion = SnmpPacket.GetProtocolVersion(Packet2, Packet2.Length);

            Assert.Equal(ESnmpVersion.Ver1, packetVersion);

            var packet = new SnmpV1Packet();

            packet.Decode(Packet2, Packet2.Length);

            Assert.Equal("public", packet.Community.ToString());

            Assert.False(packet.IsRequest);
            Assert.True(packet.IsResponse);

            Assert.Equal(38, packet.Pdu.RequestId);
            Assert.Equal(EPduErrorStatus.NoError, packet.Pdu.ErrorStatus);
            Assert.Equal(0, packet.Pdu.ErrorIndex);

            Assert.Equal(1, packet.Pdu.VbCount);

            var vb = packet.Pdu.GetVb(0);

            Assert.NotNull(vb);

            Assert.Equal(new Oid("1.3.6.1.2.1.1.2.0"), vb.Oid);
            Assert.Equal((byte)(EAsnType.Constructor | EAsnType.Sequence), vb.Type);
            Assert.Equal((byte)EAsnType.ObjectId, vb.Value.Type);
            Assert.Equal(new Oid("1.3.6.1.4.1.2001.1.1.1.297.93.1.27.2.2.1"), vb.Value);
        }
Пример #6
0
        public void Listen()
        {
            var ipEndPoint = new IPEndPoint(IPAddress.Any, 162);

            Task.Run(async() => {
                var run = true;
                while (run)
                {
                    try {
                        using (var udpListener = new UdpClient(ipEndPoint)) {
                            var udpRecieveResult = await udpListener.ReceiveAsync();
                            var recievedData     = udpRecieveResult.Buffer;

                            int protocolVersion = SnmpPacket.GetProtocolVersion(recievedData, recievedData.Length);

                            switch (protocolVersion)
                            {
                            case (int)SnmpVersion.Ver1:
                                var snmpV1TrapPacket = new SnmpV1TrapPacket();
                                snmpV1TrapPacket.decode(recievedData, recievedData.Length);
                                RecieveTrap(snmpV1TrapPacket);
                                break;

                            case (int)SnmpVersion.Ver2:
                                var snmpV2Packet = new SnmpV2Packet();
                                snmpV2Packet.decode(recievedData, recievedData.Length);
                                RecieveTrap(snmpV2Packet);
                                break;

                            case (int)SnmpVersion.Ver3:
                                var snmpV3Packet = new SnmpV3Packet();
                                snmpV3Packet.decode(recievedData, recievedData.Length);
                                RecieveTrap(snmpV3Packet);
                                break;
                            }
                        }
                    }
                    catch (SocketException) {
                        ErrorMessageBox.Show($"Port {ipEndPoint.Port} is already used.");
                        run = false;
                    }
                    catch (Exception e) {
                        ErrorMessageBox.Show($"{e.Message}");
                    }
                }
            });
        }
Пример #7
0
        public void ParseSnmpResponse8()
        {
            var packetVersion = SnmpPacket.GetProtocolVersion(Packet8, Packet8.Length);

            Assert.Equal(ESnmpVersion.Ver1, packetVersion);

            var packet = new SnmpV1Packet();

            packet.Decode(Packet8, Packet8.Length);

            Assert.Equal("public", packet.Community.ToString());

            Assert.False(packet.IsRequest);
            Assert.True(packet.IsResponse);

            Assert.Equal(41, packet.Pdu.RequestId);
            Assert.Equal(EPduErrorStatus.NoError, packet.Pdu.ErrorStatus);
            Assert.Equal(0, packet.Pdu.ErrorIndex);

            Assert.Equal(3, packet.Pdu.VbCount);

            var vb = packet.Pdu.GetVb(0);

            Assert.NotNull(vb);
            Assert.Equal(new Oid("1.3.6.1.4.1.253.8.64.4.2.1.7.10.14130104"), vb.Oid);
            Assert.Equal((byte)EAsnType.OctetString, vb.Value.Type);
            Assert.Equal(new byte[] { 0x31, 0x37, 0x32, 0x2e, 0x33, 0x31, 0x2e, 0x31, 0x39, 0x2e, 0x32 }, vb.Value as OctetString);

            vb = packet.Pdu.GetVb(1);
            Assert.NotNull(vb);
            Assert.Equal(new Oid("1.3.6.1.4.1.253.8.64.4.2.1.7.10.14130102"), vb.Oid);
            Assert.Equal((byte)EAsnType.OctetString, vb.Value.Type);
            Assert.Equal(new byte[] { 0x32, 0x35, 0x35, 0x2e, 0x32, 0x35, 0x35, 0x2e, 0x32, 0x35, 0x35, 0x2e, 0x30 }, vb.Value as OctetString);

            vb = packet.Pdu.GetVb(2);
            Assert.NotNull(vb);
            Assert.Equal(new Oid("1.3.6.1.4.1.253.8.64.4.2.1.5.10.14130400"), vb.Oid);
            Assert.Equal((byte)EAsnType.Integer, vb.Value.Type);
            Assert.Equal(1, vb.Value as Integer32);
        }
Пример #8
0
        public void Listen()
        {
            Socket     socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            IPEndPoint ipep   = new IPEndPoint(IPAddress.Any, 11000);
            EndPoint   ep     = (EndPoint)ipep;

            socket.Bind(ep);
            socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 0);
            bool run   = true;
            int  inlen = -1;

            while (run)
            {
                byte[] indata = new byte[1024 * 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);

                        _data.Cores = new List <CpuCore>();
                        for (var i = 0; i < pkt.Pdu.VbList.Count; ++i)
                        {
                            _data.Cores.Add(new CpuCore {
                                Index = i, Load = int.Parse(pkt.Pdu.VbList[i].Value.ToString())
                            });
                        }
                        //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 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
                        {
                            _data.Cores = new List <CpuCore>();
                            for (var i = 0; i < pkt.Pdu.VbList.Count; ++i)
                            {
                                _data.Cores.Add(new CpuCore {
                                    Index = i, Load = int.Parse(pkt.Pdu.VbList[i].ToString())
                                });
                            }
                        }
                    }
                }
                else
                {
                    if (inlen == 0)
                    {
                        Console.WriteLine("Zero length packet received.");
                    }
                }
            }
        }
Пример #9
0
        public void Start()
        {
            Task.Run(() =>
            {
                this._run = true;

                while (this._run)
                {
                    byte[] indata = new byte[16 * 1024];
                    // 16KB receive buffer int inlen = 0;
                    IPEndPoint peer = new IPEndPoint(IPAddress.Any, 0);

                    EndPoint inep = (EndPoint)peer;

                    int inlen = -1;
                    try
                    {
                        inlen = _socket.ReceiveFrom(indata, ref inep);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Exception {0}", ex.Message);
                        inlen = -1;
                    }
                    if (inlen > 0)
                    {
                        Task.Run(() =>
                        {
                            // Check protocol version int
                            int ver = SnmpPacket.GetProtocolVersion(indata, inlen);

                            // 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());

                            //TrapOID .1.3.6.1.4.1.368.4.1.3.1.3.1.1(TemperatureSensorStatus)

                            //Variable bindings
                            //1.3.6.1.4.1.368.4.1.3.1.3.1.1(TemperatureSensorStatus)->value = 0(NONE), 1(OK), 2(NOK)
                            //1.3.6.1.4.1.368.4.1.3.1.4.1.1(TemperatureSensorValue)->value = [-60, 100]

                            //---------------------- -

                            //TrapOID 1.3.6.1.4.1.368.4.2.0.1(AlarmStatus)

                            //Variable bindings
                            //1.3.6.1.4.1.368.4.2.0.1(AlarmStatus)->value = 0, 1, 2, 3
                            if ((SnmpSharpNet.PduType)pkt.Pdu.Type != PduType.V2Trap)
                            {
                                Console.WriteLine("*** NOT an SNMPv2 trap ****");
                            }
                            else
                            {
                                var valueReceived = pkt.Pdu.VbList.FirstOrDefault(p => p.Oid.ToString().CompareTo(pkt.Pdu.TrapObjectID.ToString()) == 0);
                                RaiseEvent(valueReceived.Oid.ToString().CompareTo(OIDAlarm) == 0 ? "Alarm" : "OperationalStatus", valueReceived.Value.ToString());

                                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.");
                        }
                    }
                }
            });
        }
Пример #10
0
        private void ReceiveCallback(IAsyncResult result)
        {
            // get a reference to the socket. This is handy if socket has been closed elsewhere in the class
            Socket sock = (Socket)result.AsyncState;

            _peerIP = new IPEndPoint(IPAddress.Any, 0);

            // variable to store received data length
            int inlen;

            try    {
                EndPoint ep = (EndPoint)_peerIP;
                inlen   = sock.EndReceiveFrom(result, ref ep);
                _peerIP = (IPEndPoint)ep;
            }
            catch (System.Exception ex)
            {
                // only post messages if class socket reference is not null
                // in all other cases, user has terminated the socket
                if (_socket != null)
                {
                    PostAsyncMessage("Receive operation failed with message: " + ex.Message);
                }
                inlen = -1;
            }
            // if socket has been closed, ignore received data and return
            if (_socket == null)
            {
                return;
            }
            // check that received data is long enough
            if (inlen <= 0)
            {
                // request next packet
                RegisterReceiveOperation();
                return;
            }
            int packetVersion = SnmpPacket.GetProtocolVersion(_inbuffer, inlen);

            if (packetVersion == (int)SnmpVersion.Ver2)
            {
                SnmpV2Packet pkt = new SnmpV2Packet();
                try  {
                    pkt.decode(_inbuffer, inlen);
                }
                catch (System.Exception ex)
                {
                    PostAsyncMessage("Error parsing SNMPv2 Trap: " + ex.Message);
                    pkt = null;
                }
                if (pkt != null)
                {
                    if (pkt.Pdu.Type == PduType.V2Trap)
                    {
                        PostAsyncMessage(String.Format("** SNMPv2 TRAP from {0}", _peerIP.ToString()));
                    }
                    if (pkt != null)
                    {
                        /*PostAsyncMessage(
                         *  String.Format("*** community {0} sysUpTime: {1} trapObjectID: {2}",
                         *      pkt.Community, pkt.Pdu.TrapSysUpTime.ToString(), pkt.Pdu.TrapObjectID.ToString())
                         * );*/
                        //PostAsyncMessage(String.Format("*** PDU count: {0}", pkt.Pdu.VbCount));
                        foreach (Vb vb in pkt.Pdu.VbList)
                        {
                            /*PostAsyncMessage(
                             *  String.Format("**** Vb oid: {0} type: {1} value: {2}",
                             *      vb.Oid.ToString(), SnmpConstants.GetTypeName(vb.Value.Type), vb.Value.ToString())
                             * );*/
                            if (vb.Oid.ToString() == "1.3.6.1.4.1.6302.3.1.46.2" ||
                                vb.Oid.ToString() == "1.3.6.1.4.1.6302.3.1.42.2")
                            {
                                // we caught the trap and foudn the one we awnt... do the business
                                PostAsyncMessage(
                                    String.Format("**** Got AC FAIL trap -> oid: {0} type: {1} value: {2}",
                                                  vb.Oid.ToString(), SnmpConstants.GetTypeName(vb.Value.Type), vb.Value.ToString()));
                                SetText(this, lbl_extPwr, "Off");
                                SetColor(this, pnl_extPwr, Color.Red);
                                updateActiveCap(true);
                            }
                            else if (vb.Oid.ToString() == "1.3.6.1.4.1.6302.3.1.42.3")
                            {
                                PostAsyncMessage(
                                    String.Format("**** Got AC RETURN Trap -> oid: {0} type: {1} value: {2}",
                                                  vb.Oid.ToString(), SnmpConstants.GetTypeName(vb.Value.Type), vb.Value.ToString()));
                                SetText(this, lbl_extPwr, "On");
                                SetColor(this, pnl_extPwr, Color.Lime);
                                updateActiveCap(false);
                            }
                        }
                        if (pkt.Pdu.Type == PduType.V2Trap)
                        {
                            PostAsyncMessage("** End of SNMPv2 TRAP");
                        }
                    }
                }
            }
            RegisterReceiveOperation();
        }
Пример #11
0
        private void AcceptTrap()
        {
            if (!isListenTrap)
            {
                return;
            }
            socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            IPEndPoint ipep = new IPEndPoint(IPAddress.Any, App.snmpTrapPort);
            EndPoint   ep   = (EndPoint)ipep;

            try
            {
                socket.Bind(ep);
            }
            catch (Exception ex)
            {
                IsListenTrap = false;
                MessageBox.Show(string.Format("打开TRAP监听端口{0}失败\n详细信息:{1}", App.snmpTrapPort, ex.Message));
                return;
            }
            SetTextBlockAsync(tbStatusMessage, string.Format("开始后台接收Trap消息,udp端口{0}", App.snmpTrapPort));
            // Disable timeout processing. Just block until packet is received
            socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 0);
            IPEndPoint peer = new IPEndPoint(IPAddress.Any, 0);
            EndPoint   inep = (EndPoint)peer;

            while (isListenTrap)
            {
                // 16KB receive buffer
                byte[] indata = new byte[16 * 1024];
                int    inlen  = 0;
                try
                {
                    inlen = socket.ReceiveFrom(indata, ref inep);//inlen为udp包的负载
                }
                catch (Exception ex)
                {
                    string errorMessage;
                    if (isListenTrap)
                    {
                        errorMessage = string.Format("异常 {0}", ex.Message);
                        SetTextBlockAsync(tbStatusMessage, errorMessage);
                    }
                    else
                    {
                        errorMessage = "后台接收Trap线程被强行终止";
                        SetTextBlockAsync(tbStatusMessage, errorMessage);
                        return;
                    }
                    inlen = -1;
                }
                if (inlen > 0)
                {
                    // Check protocol version
                    int ver = SnmpPacket.GetProtocolVersion(indata, inlen);
                    //在snmphelper中建立静态函数分别解析V1 V2的trap。。。
                    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());
                        }
                        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 (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.");
                    }
                }
            }
            SetTextBlockAsync(tbStatusMessage, "后台接收Trap线程结束");
        }
Пример #12
0
        static void Main(string[] args)
        {
            SiAuto.Si.Enabled     = true;
            SiAuto.Si.Level       = Level.Debug;
            SiAuto.Si.Connections = @"file(filename=""" + Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + "\\log.sil\",rotate=weekly,append=true,maxparts=5,maxsize=500MB)";

            // 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);
            #region sms
            var smsSendTimer = new System.Timers.Timer(5);
            smsSendTimer.Elapsed += (sender, e) =>
            {
                string result     = null;
                string deviceName = null;
                string stateId    = null;
                //ThreadPool.QueueUserWorkItem(delegate
                //{
                if (smsQueue.TryDequeue(out result))
                {
                    string[] getStrings = result.Split(new char[] { '&' });
                    if (getStrings.Length.Equals(2))
                    {
                        deviceName = getStrings[0];
                        stateId    = getStrings[1];
                        //SendStatusSMS(deviceName, stateId);
                    }
                }
                //});
            };
            smsSendTimer.Enabled = true;
            #endregion sms

            #region sendSmsIfStatusStillInSpecficTime

            /*
             * System.Timers.Timer timerSmsSend = new System.Timers.Timer();
             * //計時器啟動
             * timerSmsSend.Elapsed += new ElapsedEventHandler(timerSmsSend_Elapsed);
             * //計時器啟動 設定觸發時間
             * timerSmsSend.Interval = 60000;
             * timerSmsSend.Start();
             */
            System.Threading.Thread t1 = new System.Threading.Thread
                                             (delegate()
            {
                while (true)
                {
                    Thread.Sleep(new TimeSpan(0, 0, 1, 0));
                    timerSmsSend_Elapsed();
                }
            });
            t1.Start();
            #endregion sendSmsIfStatusStillInSpecficTime

            bool run = true;
            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)
                {
                    // 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());
                         *                      }
                         *                      Console.WriteLine("** End of SNMP Version 1 TRAP data.");
                         */
                    }
                    else
                    {
                        // Parse SNMP Version 2 TRAP packet
                        SnmpV3Packet pkt = SnmpV3Packet.DiscoveryRequest();
                        pkt.decode(indata, inlen);
                        //Console.WriteLine("** SNMP Version 3 TRAP received from {0}:", inep.ToString());
                        if (pkt.Version != SnmpVersion.Ver3)
                        {
                            Console.WriteLine("*** NOT an SNMPv3 trap ****");
                        }
                        else
                        {
                            //Console.WriteLine("*** Community: {0}", pkt.Community.ToString());
                            StringBuilder sb = new StringBuilder();

                            /*
                             * Console.WriteLine(pkt.GetType());
                             * Console.WriteLine(pkt.USM);
                             * Console.WriteLine(pkt.USM.AuthenticationSecret);
                             * Console.WriteLine(pkt.USM.PrivacySecret);
                             * Console.WriteLine(pkt.Pdu.RequestId);
                             * Console.WriteLine(pkt.USM.EngineId);
                             * Console.WriteLine(pkt.USM.SecurityName);
                             * Console.WriteLine(pkt.ScopedPdu.ContextEngineId);
                             * Console.WriteLine(pkt.ScopedPdu.ContextName);
                             * Console.WriteLine("trapSysUpTime.0: {0}", pkt.Pdu.TrapSysUpTime.ToString());
                             * Console.WriteLine("trapObjectID.0 : {0}", pkt.Pdu.TrapObjectID.ToString());
                             *                          Console.WriteLine("*** VarBind count: {0}", pkt.Pdu.VbList.Count);
                             *                          Console.WriteLine("*** VarBind content:");
                             */
                            string serverityLevel = null, ipAddress = null, eventMessage = null, location = null;
                            foreach (Vb v in pkt.Pdu.VbList)
                            {
                                //Console.WriteLine("**** {0} {1}: {2}", v.Oid.ToString(), SnmpConstants.GetTypeName(v.Value.Type),v.Value.ToString());
                                sb.Append(v.Oid.ToString()).Append(" = ").Append(v.Value.ToString()).AppendLine();
                                switch (v.Oid.ToString())
                                {
                                case "1.3.6.1.4.1.161.3.10.105.9.0":    //severity level
                                    serverityLevel = v.Value.ToString();
                                    break;

                                case "1.3.6.1.4.1.161.3.10.105.8.0":    //location
                                    location = v.Value.ToString();
                                    break;

                                case "1.3.6.1.4.1.161.3.10.105.10.0":    //IpAddress
                                    try
                                    {
                                        string ip = v.Value.ToString();
                                        string ValidIpAddressRegex = @"^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)";
                                        Regex  r = new Regex(ValidIpAddressRegex, RegexOptions.IgnoreCase | RegexOptions.Singleline);

                                        Match m = r.Match(ip);
                                        if (m.Success)
                                        {
                                            //Console.WriteLine(m.Value + " valid");
                                            ipAddress = m.Value;
                                            ipAddress = ip;
                                        }
                                        else
                                        {
                                            //Console.WriteLine("invalid");
                                        }
                                    }
                                    catch (Exception)
                                    {
                                        throw;
                                    }
                                    break;

                                case "1.3.6.1.4.1.161.3.10.105.13.0":    //event message
                                    eventMessage = v.Value.ToString().Replace(@"'", @"''");
                                    break;
                                }
                            }
                            Console.WriteLine("serverityLevel:" + serverityLevel +
                                              Environment.NewLine + "location:" + location + Environment.NewLine +
                                              "eventMessage:" + eventMessage);
                            if (serverityLevel.Equals("0"))
                            {
                                SiAuto.Main.LogWarning("serverityLevel:" + serverityLevel +
                                                       Environment.NewLine + "location:" + location + Environment.NewLine +
                                                       "eventMessage:" + eventMessage);
                            }
                            if (smsSB.ToString().Equals(location + "&" + serverityLevel))
                            {
                                //do nothing
                            }
                            else
                            {
                                if (serverityLevel != null && location != null && eventMessage != null)
                                {
                                    Thread writeCurrentDeviceStatusThread = new System.Threading.Thread
                                                                                (delegate()
                                    {
                                        //update device
                                        string DeviceNo      = null;
                                        string SiteCName     = null;
                                        string DeviceCName   = null;
                                        string queryDeviceNo = @"SELECT
public.device_info.device_no,
public.site_info_nbi.site_name,
public.device_base.device_cname
FROM
public.device_info
INNER JOIN public.site_info_nbi ON public.device_info.site_id = public.site_info_nbi.site_id
INNER JOIN public.device_base ON public.device_info.device_id = public.device_base.device_id
WHERE
public.device_info.device_name ='" + location + "'";
                                        try
                                        {
                                            using (DataTable dt = pgsqSqlClient.get_DataTable(queryDeviceNo))
                                            {
                                                if (dt != null && dt.Rows.Count != 0)
                                                {
                                                    foreach (DataRow row in dt.Rows)
                                                    {
                                                        DeviceNo    = row[0].ToString();
                                                        SiteCName   = row[1].ToString();
                                                        DeviceCName = row[2].ToString();
                                                    }
                                                }
                                            }
                                            if (DeviceNo != null && !serverityLevel.Equals("7"))
                                            {
                                                string checkIfDeviceNoExistInStatusTable = @"SELECT
public.device_status_now.device_no
FROM
public.device_status_now
WHERE
public.device_status_now.device_no = " + DeviceNo;
                                                using (DataTable dt = pgsqSqlClient.get_DataTable(checkIfDeviceNoExistInStatusTable))
                                                {
                                                    if (dt != null && dt.Rows.Count != 0)
                                                    {
                                                        string queryDeviceStatusBySpecificDeviceNo = @"SELECT
public.device_status_now.status_code
FROM
public.device_status_now
WHERE
public.device_status_now.device_no = " + DeviceNo;
                                                        using (DataTable dt2 = pgsqSqlClient.get_DataTable(queryDeviceStatusBySpecificDeviceNo))
                                                        {
                                                            string stateResult = string.Empty;
                                                            if (dt2 != null && dt2.Rows.Count != 0)
                                                            {
                                                                stateResult = dt2.Rows[0].ItemArray[0]
                                                                              .ToString();
                                                                string updateSqlScript = null;
                                                                if (stateResult.Equals(serverityLevel))
                                                                {
                                                                    //do nothing
                                                                }
                                                                else
                                                                {
                                                                    //update
                                                                    updateSqlScript = @"UPDATE public.device_status_now SET status_code = " + serverityLevel + @" ,message = '" + eventMessage + @"' " + @",update_time=now(),site_and_device_name='" + SiteCName + " " + DeviceCName + @"',send_status = 0 WHERE device_no = " + DeviceNo;
                                                                    pgsqSqlClient.modify(updateSqlScript);
                                                                    //send sms
                                                                    //if (serverityLevel.Equals("1") || serverityLevel.Equals("2"))
                                                                    {
                                                                        SiAuto.Main.AddCheckpoint("location & serverityLevel", smsSB.ToString());
                                                                        smsSB.Clear();
                                                                        smsSB.Insert(0, location + "&" + serverityLevel);
                                                                        SiAuto.Main.AddCheckpoint("location-serverityLevel-eventMessage", "location:" + location + Environment.NewLine + "serverityLevel:" + serverityLevel + Environment.NewLine + "eventMessage:" + eventMessage);
                                                                        smsQueue.Enqueue(SiteCName + " " + DeviceCName + "&" + serverityLevel);
                                                                    }
                                                                }
                                                            }
                                                        }
                                                    }
                                                    else
                                                    {
                                                        //insert
                                                        string insertSqlScript = @"INSERT INTO public.device_status_now VALUES (" + DeviceNo + @"," + serverityLevel + @",'" + eventMessage + "'" + @",now(),0,'" + SiteCName + " " + DeviceCName + @"')";
                                                        pgsqSqlClient.modify(insertSqlScript);
                                                        //send sms
                                                        //if (serverityLevel.Equals("1") || serverityLevel.Equals("2"))
                                                        {
                                                            SiAuto.Main.AddCheckpoint("location & serverityLevel", smsSB.ToString());
                                                            smsSB.Clear();
                                                            smsSB.Insert(0, location + "&" + serverityLevel);
                                                            SiAuto.Main.AddCheckpoint("location-serverityLevel-eventMessage", "location:" + location + Environment.NewLine + "serverityLevel:" + serverityLevel + Environment.NewLine + "eventMessage:" + eventMessage);
                                                            smsQueue.Enqueue(SiteCName + " " + DeviceCName + "&" + serverityLevel);
                                                        }
                                                    }
                                                }
                                                string querySiteID = @"SELECT
public.device_info.site_id
FROM
public.device_info
WHERE
public.device_info.device_no =" + DeviceNo;
                                                string siteID      = null;
                                                using (DataTable dt = pgsqSqlClient.get_DataTable(querySiteID))
                                                {
                                                    if (dt != null && dt.Rows.Count != 0)
                                                    {
                                                        foreach (DataRow row in dt.Rows)
                                                        {
                                                            siteID = row[0].ToString();
                                                        }
                                                    }
                                                }
                                                if (siteID != null)
                                                {
                                                    string queryDeviceList = @"SELECT device_no
FROM
device_info
WHERE
site_id=" + siteID;
                                                    List <int> deviceList  = new List <int>();
                                                    using (DataTable dt = pgsqSqlClient.get_DataTable(queryDeviceList))
                                                    {
                                                        if (dt != null && dt.Rows.Count != 0)
                                                        {
                                                            foreach (DataRow row in dt.Rows)
                                                            {
                                                                deviceList.Add(int.Parse(row[0].ToString()));
                                                            }
                                                        }
                                                    }
                                                    List <int> statusList    = new List <int>();
                                                    string queryDeviceStatus = @"SELECT
public.device_status_now.status_code
FROM
public.device_status_now
WHERE
public.device_status_now.device_no = ";
                                                    for (int i = 0; i < deviceList.Count; i++)
                                                    {
                                                        using (DataTable dt = pgsqSqlClient.get_DataTable(queryDeviceStatus + deviceList[i]))
                                                        {
                                                            if (dt != null && dt.Rows.Count != 0)
                                                            {
                                                                foreach (DataRow row in dt.Rows)
                                                                {
                                                                    statusList.Add(int.Parse(row[0].ToString()));
                                                                }
                                                            }
                                                        }
                                                    }
                                                    statusList.Sort();
                                                    string checkIfSiteIDExist = @"SELECT
public.site_status_now_nbi.site_id
FROM
public.site_status_now_nbi
WHERE
public.site_status_now_nbi.site_id = " + siteID;
                                                    using (DataTable dt = pgsqSqlClient.get_DataTable(checkIfSiteIDExist))
                                                    {
                                                        if (dt != null && dt.Rows.Count != 0)
                                                        {
                                                        }
                                                        else
                                                        {
                                                            string insertSiteID = @"INSERT INTO site_status_now_nbi VALUES(" + siteID + @",100)";
                                                            pgsqSqlClient.modify(insertSiteID);
                                                        }
                                                    }
                                                    string getWorstStatus = @"SELECT
public.site_status_now_nbi.status_code
FROM
public.site_status_now_nbi
WHERE
public.site_status_now_nbi.site_id = " + siteID;
                                                    using (DataTable dt = pgsqSqlClient.get_DataTable(getWorstStatus))
                                                    {
                                                        if (dt != null && dt.Rows.Count != 0)
                                                        {
                                                            string updateSiteIDStatus = @"UPDATE site_status_now_nbi SET status_code = " + statusList[0] + @" WHERE site_id=" + siteID + ";";
                                                            string updateLinkStatus   = @"UPDATE link_status_now_nbi
SET status_code = " + statusList[0] + @" 
WHERE
	bsite_id = "     + siteID + ";";
                                                            pgsqSqlClient.modify(updateSiteIDStatus + updateLinkStatus);
                                                        }
                                                        else
                                                        {
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                        catch (Exception e)
                                        {
                                            Console.WriteLine(e.ToString());
                                            SiAuto.Main.LogException(e);
                                        }
                                    });
                                    Thread writeToHistoryThread = new System.Threading.Thread
                                                                      (delegate()
                                    {
                                        string DeviceNo      = null;
                                        string queryDeviceNo = @"SELECT
public.device_info.device_no
FROM
public.device_info
WHERE
public.device_info.device_name = '" + location + "'";
                                        try
                                        {
                                            using (DataTable dt = pgsqSqlClient.get_DataTable(queryDeviceNo))
                                            {
                                                if (dt != null && dt.Rows.Count != 0)
                                                {
                                                    foreach (DataRow row in dt.Rows)
                                                    {
                                                        DeviceNo = row[0].ToString();
                                                    }
                                                }
                                            }
                                            string insertSqlScript = null;
                                            if (DeviceNo != null)
                                            {
                                                insertSqlScript = @"INSERT INTO device_status_history_nbi (
	device_no,
	alarm_status,
	message_note
)
VALUES
	("     + DeviceNo + @", " + serverityLevel + @", '" + eventMessage + "')";
                                                pgsqSqlClient.modify(insertSqlScript);
                                            }
                                        }
                                        catch (Exception e)
                                        {
                                        }
                                    });
                                    writeCurrentDeviceStatusThread.Start();
                                    writeToHistoryThread.Start();
                                    writeCurrentDeviceStatusThread.Join();
                                    writeToHistoryThread.Join();
                                }
                            }

                            if (serverityLevel != null && location != null && ipAddress != null && eventMessage != null && false)
                            {
                                if (!File.Exists(Environment.CurrentDirectory + "\\" + DateTime.Now.ToString("yy-MM-dd") + ".csv"))
                                {
                                    using (StreamWriter sw = new StreamWriter(Environment.CurrentDirectory + "\\" + DateTime.Now.ToString("yy-MM-dd") + ".csv", true))
                                    {
                                        var csv = new CsvWriter(sw);
                                        csv.WriteField("serverityLevel");
                                        csv.WriteField("location");
                                        csv.WriteField("ipAddress");
                                        csv.WriteField("eventMessage");
                                        csv.NextRecord();
                                    }
                                }
                                using (StreamWriter sw = new StreamWriter(Environment.CurrentDirectory + "\\" + DateTime.Now.ToString("yy-MM-dd") + ".csv", true))
                                {
                                    var csv = new CsvWriter(sw);
                                    csv.WriteField(serverityLevel);
                                    csv.WriteField(location);
                                    csv.WriteField(ipAddress);
                                    csv.WriteField(eventMessage);
                                    csv.NextRecord();
                                }
                            }
                            //SiAuto.Main.LogStringBuilder("receive trp",sb);
                            //Console.WriteLine("receive trp:"+Environment.NewLine+sb.ToString());
                            //Console.WriteLine("** End of SNMP Version 3 TRAP data.");
                        }
                    }
                }
                else
                {
                    if (inlen == 0)
                    {
                        Console.WriteLine("Zero length packet received.");
                    }
                }
            }
        }
Пример #13
0
        private void device_OnPacketArrival(object sender, CaptureEventArgs packet)
        {
            Packet    pack      = Packet.ParsePacket(packet.Packet.LinkLayerType, packet.Packet.Data);
            TcpPacket tcpPacket = (TcpPacket)pack.Extract(typeof(TcpPacket));

            DateTime time = packet.Packet.Timeval.Date;
            int      len  = packet.Packet.Data.Length;

            if (tcpPacket != null)
            {
                IpPacket ipPacket = (IpPacket)tcpPacket.ParentPacket;

                var packageDetail = new PackageDetail(tcpPacket, null, ipPacket);
                packageDetailList.Add(packageDetail);

                var srcIp   = ipPacket.SourceAddress;
                var dstIp   = ipPacket.DestinationAddress;
                var srcPort = tcpPacket.SourcePort;
                var dstPort = tcpPacket.DestinationPort;
                writeLine = string.Format("ID: {9} - {0}:{1}:{2},{3} - TCP Packet: {5}:{6}  -> {7}:{8}\n\n",
                                          time.Hour, time.Minute, time.Second, time.Millisecond, len,
                                          srcIp, srcPort, dstIp, dstPort, packageDetail.Id);
                Invoke(new MethodInvoker(updateLog));
            }
            else
            {
                UdpPacket udpPacket = (UdpPacket)pack.Extract(typeof(UdpPacket));
                time = packet.Packet.Timeval.Date;
                len  = packet.Packet.Data.Length;
                if (udpPacket != null)
                {
                    IpPacket ipPacket = (IpPacket)udpPacket.ParentPacket;

                    var packageDetail = new PackageDetail(null, udpPacket, ipPacket);
                    packageDetailList.Add(packageDetail);

                    IPAddress srcIp   = ipPacket.SourceAddress;
                    IPAddress dstIp   = ipPacket.DestinationAddress;
                    ushort    srcPort = udpPacket.SourcePort;
                    ushort    dstPort = udpPacket.DestinationPort;
                    writeLine = (string.Format("ID: {9} - {0}:{1}:{2},{3} - UDP Packet: {5}:{6} -> {7}:{8}\n",
                                               time.Hour, time.Minute, time.Second, time.Millisecond, len,
                                               srcIp, srcPort, dstIp, dstPort, packageDetail.Id));
                    Invoke(new MethodInvoker(updateLog));
                    if (decodeMode == true)
                    {
                        byte[] packetBytes = udpPacket.PayloadData;
                        int    version     = SnmpPacket.GetProtocolVersion(packetBytes, packetBytes.Length);
                        switch (version)
                        {
                        case (int)SnmpVersion.Ver1:
                            SnmpV1Packet snmpPacket = new SnmpV1Packet();
                            try
                            {
                                snmpPacket.decode(packetBytes, packetBytes.Length);
                                writeLine = "SNMP.V1 Packet: " + snmpPacket.ToString();
                            }
                            catch (Exception e)
                            {
                                writeLine = e.ToString();
                            }
                            break;

                        case (int)SnmpVersion.Ver2:
                            SnmpV2Packet snmp2Packet = new SnmpV2Packet();
                            try
                            {
                                snmp2Packet.decode(packetBytes, packetBytes.Length);
                                writeLine = "SNMP.V2 Packet: " + snmp2Packet.ToString();
                            }
                            catch (Exception e)
                            {
                                writeLine = e.ToString();
                            }
                            break;

                        case (int)SnmpVersion.Ver3:
                            SnmpV3Packet snmp3Packet = new SnmpV3Packet();
                            try
                            {
                                snmp3Packet.decode(packetBytes, packetBytes.Length);
                                writeLine = "SNMP.V3 Packet: " + snmp3Packet.ToString();
                            }
                            catch (Exception e)
                            {
                                writeLine = e.ToString();
                            }
                            break;
                        }
                        Invoke(new MethodInvoker(updateLog));
                    }
                }
            }
        }
Пример #14
0
        public void trapReceiver()
        {
            Socket     socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            IPEndPoint ipep   = new IPEndPoint(IPAddress.Any, 162);
            EndPoint   ep     = (EndPoint)ipep;

            socket.Bind(ep);

            socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 0);
            bool run   = true;
            int  inlen = -1;

            while (run)
            {
                byte[]     indata    = new byte[16 * 1024];
                IpAddress  addressIP = new IpAddress(address);
                IPEndPoint peer      = new IPEndPoint((IPAddress)addressIP, 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)
                {
                    int ver = SnmpPacket.GetProtocolVersion(indata, inlen);
                    if (ver == (int)SnmpVersion.Ver1)
                    {
                        SnmpV1TrapPacket pkt  = new SnmpV1TrapPacket();
                        string           date = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                        List <VarBind>   varBindContentList = new List <VarBind>();
                        pkt.decode(indata, inlen);

                        foreach (Vb v in pkt.Pdu.VbList)
                        {
                            varBindContentList.Add(new VarBind(v.Oid.ToString(), SnmpConstants.GetTypeName(v.Value.Type), v.Value.ToString()));
                        }
                        string ruleName = "NULL";
                        varBindListPerTrap.Add(trapCounter, varBindContentList);
                        windowHandler.addTrap(getGenericType(pkt.Pdu.Generic), pkt.Pdu.AgentAddress.ToString(), date, ruleName);
                        trapCounter++;
                    }
                    else
                    {
                        SnmpV2Packet   pkt  = new SnmpV2Packet();
                        string         date = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                        List <VarBind> varBindContentList = new List <VarBind>();
                        pkt.decode(indata, inlen);

                        if ((SnmpSharpNet.PduType)pkt.Pdu.Type != PduType.V2Trap)
                        {
                        }
                        else
                        {
                            foreach (Vb v in pkt.Pdu.VbList)
                            {
                                varBindContentList.Add(new VarBind(v.Oid.ToString(), SnmpConstants.GetTypeName(v.Value.Type), v.Value.ToString()));
                            }
                            string ruleName = "NULL";
                            varBindListPerTrap.Add(trapCounter, varBindContentList);
                            windowHandler.addTrap(pkt.Pdu.TrapObjectID.ToString(), "?", date, ruleName);
                            trapCounter++;
                        }
                    }
                }
                else
                {
                    if (inlen == 0)
                    {
                        Console.WriteLine("Zero length packet received.");
                    }
                }
            }
        }
Пример #15
0
    /// <summary>
    /// Thread that will keep listening for traps
    /// </summary>
    public void TrapThread()
    {
        // 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, 16009);
        EndPoint   ep     = (EndPoint)ipep;

        socket.Bind(ep);
        // Disable timeout processing. Just block until packet is received
        socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 0);
        run_trap_thread = true;
        int inlen = -1;

        while (run_trap_thread)
        {
            byte[] indata = new byte[16 * 1024];
            // 16KB receive buffer int inlen = 0;
            IPEndPoint peer = new IPEndPoint(IPAddress.Any, 0);
            EndPoint   inep = (EndPoint)peer;

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

            if (inlen > 0)
            {
                // Check protocol version int
                int ver = SnmpPacket.GetProtocolVersion(indata, inlen);
                // Parse SNMP Version 1 TRAP packet
                SnmpV1TrapPacket pkt = new SnmpV1TrapPacket();
                pkt.decode(indata, inlen);

                string underAttackOid = "1";
                string foundEnemyOid  = "2";
                string headOid        = "5.1";
                string legsOid        = "5.2";
                string armsOid        = "5.3";


                foreach (Vb v in pkt.Pdu.VbList)
                {
                    Debug.Log("for each vb");

                    switch (v.Oid.ToString())
                    {
                    case "1.3.2.5." + "1":
                        underAttack = int.Parse(v.Value.ToString());
                        break;


                    // found enemy
                    case "1.3.2.5." + "2":
                        foundEnemy = int.Parse(v.Value.ToString());
                        break;

                    // head bellow 50
                    case "1.3.2.5." + "5.1":
                        healthWarning = 1;
                        HeadHealth    = int.Parse(v.Value.ToString());
                        break;

                    // head bellow 25
                    case "1.3.2.5." + "5.2":
                        healthWarning = 1;
                        LegsHealth    = int.Parse(v.Value.ToString());
                        break;

                    // head destroyed
                    case "1.3.2.5." + "5.3":
                        healthWarning = 1;
                        ArmHealth     = int.Parse(v.Value.ToString());
                        break;
                    }
                }
            }
            else
            {
                if (inlen == 0)
                {
                    Console.WriteLine("Zero length packet received.");
                }
            }
        }
        Debug.Log(" trap thread EXITT");
    }
Пример #16
0
        public void initializeTrapListener(DataGridView table, RichTextBox rtb)
        {
            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) { }

                if (inlen > 0)
                {
                    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);

                        int n = 0;
                        table.Invoke(new Action(delegate() { n = table.Rows.Add(); }));
                        string oid        = "." + pkt.Pdu.Enterprise.ToString() + "." + pkt.Pdu.Specific.ToString();
                        var    objectName = Program.mibObjects.FirstOrDefault(x => x.Value == oid).Key;
                        if (objectName != null)
                        {
                            table.Invoke(new Action(delegate() { table.Rows[n].Cells[0].Value = "Specific: " + pkt.Pdu.Specific + "; " + objectName; }));
                        }
                        else
                        {
                            table.Invoke(new Action(delegate() { table.Rows[n].Cells[0].Value = "Specific: " + pkt.Pdu.Specific + "; " + oid; }));
                        }
                        table.Invoke(new Action(delegate() { table.Rows[n].Cells[1].Value = pkt.Pdu.AgentAddress.ToString(); }));
                        table.Invoke(new Action(delegate() { table.Rows[n].Cells[2].Value = pkt.Pdu.TimeStamp.ToString(); }));
                        table.Invoke(new Action(delegate() { table.FirstDisplayedScrollingRowIndex = table.RowCount - 1; }));
                        table.Invoke(new Action(delegate() { table.Rows[table.Rows.Count - 1].Selected = true; }));

                        rtb.Invoke(new Action(delegate() { rtb.Clear(); }));
                        writeToRtb("Source: " + pkt.Pdu.AgentAddress.ToString() + "\n", rtb);
                        writeToRtb("Timestamp: " + pkt.Pdu.TimeStamp.ToString() + "\n", rtb);
                        writeToRtb("SNMP Version: " + pkt.Version + "\n", rtb);
                        writeToRtb("Enterprise: " + pkt.Pdu.Enterprise + "\n", rtb);
                        writeToRtb("Community: " + pkt.Community + "\n", rtb);
                        writeToRtb("Specific: " + pkt.Pdu.Specific + "\n", rtb);
                        writeToRtb("Generic: " + pkt.Pdu.Generic + "\n", rtb);
                        //writeToRtb("Description: " + "tu opis kij wie skad kij wie jak" + "\n", rtb);
                    }
                    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.");
                }
            }
        }
Пример #17
0
        public TrapMessage Handler(AbstractSocketData socketData)
        {
            if (socketData == null)
            {
                return(null);
            }
            TrapMessage result;

            try
            {
                int         dataLenth       = socketData.DataLenth;
                byte[]      dataBytes       = socketData.DataBytes;
                int         protocolVersion = SnmpPacket.GetProtocolVersion(dataBytes, dataLenth);
                TrapMessage trapMessage;
                SnmpPacket  snmpPacket;
                if (protocolVersion == 0)
                {
                    trapMessage = new TrapV1Message();
                    snmpPacket  = new SnmpV1TrapPacket();
                    ((SnmpV1TrapPacket)snmpPacket).decode(dataBytes, dataLenth);
                }
                else
                {
                    if (protocolVersion == 1)
                    {
                        trapMessage = new TrapV2Message();
                        snmpPacket  = new SnmpV2Packet();
                        ((SnmpV2Packet)snmpPacket).decode(dataBytes, dataLenth);
                        if (snmpPacket.Pdu.Type != PduType.V2Trap)
                        {
                            throw new SnmpException("Invalid SNMP version 2 packet type received.");
                        }
                    }
                    else
                    {
                        trapMessage = new TrapV3Message();
                        snmpPacket  = new SnmpV3Packet();
                        UserSecurityModel uSM = ((SnmpV3Packet)snmpPacket).GetUSM(dataBytes, dataLenth);
                        if (uSM.EngineId.Length <= 0)
                        {
                            throw new SnmpException("Invalid packet. Authoritative engine id is not set.");
                        }
                        if (uSM.SecurityName.Length <= 0)
                        {
                            throw new SnmpException("Invalid packet. Security name is not set.");
                        }
                        if (this.usmConfigs.Count > 0)
                        {
                            UsmConfig usmConfig = this.FindPeer(uSM.EngineId.ToString(), uSM.SecurityName.ToString());
                            if (usmConfig == null)
                            {
                                throw new SnmpException("SNMP packet from unknown peer.");
                            }
                            ((SnmpV3Packet)snmpPacket).USM.Authentication = (AuthenticationDigests)usmConfig.Authentication;
                            ((SnmpV3Packet)snmpPacket).USM.Privacy        = (PrivacyProtocols)usmConfig.Privacy;
                            if (usmConfig.Privacy != Privacy.None)
                            {
                                ((SnmpV3Packet)snmpPacket).USM.PrivacySecret.Set(usmConfig.PrivacySecret);
                            }
                            if (usmConfig.Authentication != Authentication.None)
                            {
                                ((SnmpV3Packet)snmpPacket).USM.AuthenticationSecret.Set(usmConfig.AuthenticationSecret);
                            }
                        }
                        ((SnmpV3Packet)snmpPacket).decode(dataBytes, dataLenth);
                        if (snmpPacket.Pdu.Type != PduType.V2Trap)
                        {
                            throw new SnmpException("Invalid SNMP version 3 packet type received.");
                        }
                    }
                }
                trapMessage.AgentIpAddress = socketData.Target;
                trapMessage.Port           = socketData.Port;
                SnmpTrapHandler.configTrap(trapMessage, protocolVersion, snmpPacket);
                this.configVb(trapMessage, protocolVersion, snmpPacket);
                result = trapMessage;
            }
            catch (System.Exception ex)
            {
                System.Console.WriteLine(ex.Message);
                result = null;
            }
            return(result);
        }
Пример #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.");
                    }
                }
            }
        }
Пример #19
0
        /// <summary>
        /// 接收Trap信息;
        /// </summary>
        static private void WaitTrap()
        {
            // 建立一个Socket实例,接收所有网口的IP地址,并绑定162端口;
            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);

            int           inlen = -1;
            List <string> Ret   = new List <string>();

            while (WaitTrapRunstate)
            {
                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;
                }

                // 如果inlen大于0则证明接收到Trap;
                if (inlen > 0)
                {
                    // Check protocol version int
                    int ver = SnmpPacket.GetProtocolVersion(indata, inlen);
                    if (ver == (int)SnmpVersion.Ver1)
                    {
                        Console.WriteLine("** Receive 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());
                                string temp = "接收到Trap: Oid:" + v.Oid.ToString() + ", TypeName:" +
                                              SnmpConstants.GetTypeName(v.Value.Type) + ", Value:" + v.Value.ToString();

                                Ret.Add(temp);
                            }
                            // 通知观察者;
                            Nodify(Ret);
                        }
                    }
                }
                else
                {
                    if (inlen == 0)
                    {
                        Console.WriteLine("Zero length packet received.");
                    }
                }
            }
            Console.WriteLine("Trap waiting thread: terminating gracefully.");
        }
Пример #20
0
        public TrapListen()
        {
            using (IDbConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["DeviceConnection"].ConnectionString))
            {
                mibTreeInformation = connection.Query <MibTreeInformation>("select * from TreeInformation").ToList();
                towerDevices       = connection.Query <TowerDevices>("select * from TowerDevices").ToList();
                alarmLog           = connection.Query <AlarmLogStatus>("select * from AlarmLogStatus").ToList();

                Socket     socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                IPEndPoint ipep   = new IPEndPoint(IPAddress.Any, 162);
                EndPoint   ep     = (EndPoint)ipep;
                socket.Bind(ep);
                socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 0);

                bool run   = true;
                int  inlen = -1;
                while (run)
                {
                    alarmLog = connection.Query <AlarmLogStatus>("select * from AlarmLogStatus").ToList();

                    byte[] indata = new byte[16 * 1024];

                    IPEndPoint peer = new IPEndPoint(IPAddress.Any, 0);
                    EndPoint   inep = (EndPoint)peer;
                    try
                    {
                        inlen = socket.ReceiveFrom(indata, ref inep);
                    }
                    catch (Exception ex)
                    {
                        inlen = -1;
                    }
                    if (inlen > 0)
                    {
                        int ver = SnmpPacket.GetProtocolVersion(indata, inlen);
                        if (ver == 0)
                        {
                            try
                            {
                                SnmpV1TrapPacket pkt = new SnmpV1TrapPacket();
                                pkt.decode(indata, inlen);
                                new SnmpVersionOne(pkt, inep, mibTreeInformation, towerDevices, alarmLog);
                            }
                            catch (Exception e)
                            {
                            }
                        }

                        if (ver == 2 || ver == 1)
                        {
                            try
                            {
                                SnmpV2Packet pkt = new SnmpV2Packet();
                                pkt.decode(indata, inlen);
                                new SnmpVersionTwo(pkt, inep, mibTreeInformation, towerDevices, alarmLog);
                            }
                            catch (Exception e)
                            {
                            }
                        }
                    }
                }
            }
        }
Пример #21
0
        ///<summary>
        ///Actual work in backgroundworker thread
        ///</summary>
        private void worker_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;

            // Construct a socket and bind it to the trap manager port 10162
            Socket     socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            IPEndPoint ipep   = new IPEndPoint(IPAddress.Any, 10162);
            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;
            int  ver;

            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)
                {
                    // Check protocol version 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());
                            string   voltage = v.Value.ToString();
                            double   max     = 3.3;
                            string[] values  = voltage.Split('V');
                            _worker.ReportProgress((int)Math.Floor((double)((double.Parse(values[0], CultureInfo.InvariantCulture) / max * 100))));
                            currentVoltage = voltage;
                            double test = double.Parse(values[0]);
                            voltageLine.Points.Add(new DataPoint(double.Parse(pkt.Pdu.TimeStamp.ToString()), double.Parse(values[0], CultureInfo.InvariantCulture)));
                            model.RefreshPlot(true);
                        }
                        Console.WriteLine("** End of SNMP Version 1 TRAP data.");
                    }
                }
                else
                {
                    if (inlen == 0)
                    {
                        Console.WriteLine("Zero length packet received.");
                    }
                }
            }
            Yield(1000000);
        }
Пример #22
0
        private static void DoWork()
        {
            // 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);

            while (true)
            {
                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)
                {
                    Functions.AddTempLog(new List <string> {
                        ex.Message, ex.ToString()
                    });
                    inlen = -1;
                }
                if (inlen > 0)
                {
                    // Check protocol version
                    int ver = SnmpPacket.GetProtocolVersion(indata, inlen);
                    if (ver == (int)SnmpVersion.Ver2)
                    {
                        // Parse SNMP Version 2 TRAP packet
                        SnmpV2Packet pkt = new SnmpV2Packet();
                        pkt.decode(indata, inlen);
                        List <string> alarm = new List <string> {
                            inep.ToString(), pkt.Community.ToString()
                        };
                        List <string> trap = new List <string>();
                        foreach (Vb v in pkt.Pdu.VbList)
                        {
                            trap.Add(v.Value.ToString());
                        }
                        Functions.AddTempLog(trap);

                        if (trap.Count == 42)
                        {
                            IPCom     _ipcom     = new IPCom();
                            CiscoPort _ciscoPort = new CiscoPort();

                            string path = "C:\\Repository.db";
                            string _connectionString;
                            _connectionString = "Data Source=" + path + ";Version=3;";
                            using (var connection = new SQLiteConnection(_connectionString))
                            {
                                connection.Open();

                                using (var command = new SQLiteCommand("SELECT IP,Com,PortId FROM Ports WHERE JDSUPort = @_JDSUPort", connection))
                                {
                                    command.Parameters.Add("@_JDSUPort", DbType.String).Value = trap[27];



                                    try
                                    {
                                        using (var reader = command.ExecuteReader())
                                        {
                                            // int k = (int)command.ExecuteScalar();

                                            foreach (DbDataRecord record in reader)
                                            {
                                                try
                                                {
                                                    SimpleSnmp snmp = new SimpleSnmp(record["IP"].ToString(), record["Com"].ToString());



                                                    Pdu pdu = new Pdu(PduType.Set);
                                                    pdu.VbList.Add(new Oid(".1.3.6.1.2.1.2.2.1.7" + record["PortId"].ToString()), new Integer32(2));
                                                    snmp.Set(SnmpVersion.Ver2, pdu);
                                                }
                                                catch (Exception ex)
                                                {
                                                    alarm.Add(ex.ToString());
                                                }


                                                alarm.Add(record["IP"].ToString());
                                                alarm.Add(record["Com"].ToString());
                                                alarm.Add(record["PortId"].ToString());
                                                alarm.Add(trap[27].ToString());
                                            }
                                        }
                                    }

                                    catch (Exception ex)
                                    {
                                        alarm.Add(ex.ToString());
                                        alarm.Add("в базе данных нет такой записи");
                                    }
                                }
                            }
                            //  Functions.AddTempLog(alarm);
                        }
                        else
                        {
                            if (inlen == 0)
                            {
                                Functions.AddTempLog(new List <string> {
                                    "Zero length packet received."
                                });
                            }
                        }
                    }
                }
            }
        }
Пример #23
0
        public void TrapReceivedSNMPAgentNotify()
        {
            runTrap = true;
            if (isNotBindedPort)
            {
                socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 162);
                EndPoint   ep   = (EndPoint)ipep;
                socket.Bind(ep);

                socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 0);
                isNotBindedPort = false;
            }
            int inlen = -1;

            while (runTrap)
            {
                DateTime time   = DateTime.Now;
                byte[]   indata = new byte[16 * 1024];

                IPEndPoint peer = new IPEndPoint(IPAddress.Any, 0);
                EndPoint   inep = (EndPoint)peer;
                try
                {
                    inlen = socket.ReceiveFrom(indata, ref inep);
                    time  = DateTime.Now;
                }
                catch (Exception ex)
                {
                    inlen = -1;
                }
                if (inlen > 0)
                {
                    int ver = SnmpPacket.GetProtocolVersion(indata, inlen);
                    if (ver == (int)SnmpVersion.Ver1)
                    {
                        SnmpV1TrapPacket pkt = new SnmpV1TrapPacket();
                        pkt.decode(indata, inlen);

                        foreach (Vb v in pkt.Pdu.VbList)
                        {
                            addRowToAgentNotify(pkt.Pdu.AgentAddress.ToString(), v.Oid.ToString(), v.Value.ToString(),
                                                time, pkt.Pdu.Generic);
                        }
                    }
                    else
                    {
                        // Parse SNMP Version 2 TRAP packet
                        SnmpV2Packet pkt = new SnmpV2Packet();
                        pkt.decode(indata, inlen);
                        if ((PduType)pkt.Pdu.Type != PduType.V2Trap)
                        {
                        }
                        else
                        {
                            foreach (Vb v in pkt.Pdu.VbList)
                            {
                                addRowToAgentNotify("", v.Oid.ToString(), v.Value.ToString(),
                                                    time, "");
                            }
                        }
                    }
                }
            }
        }