Пример #1
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}");
                    }
                }
            });
        }
Пример #2
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线程结束");
        }
Пример #3
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)
                            {
                            }
                        }
                    }
                }
            }
        }
Пример #4
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);
        }
Пример #5
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.");
                    }
                }
            }
        }
Пример #6
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.");
                    }
                }
            }
        }
Пример #7
0
        public static void Main(string[] args)
        {
            // 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)
            {
                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)
                {
                    using (SqlConnection conn = new SqlConnection())
                    {
                        conn.ConnectionString = "Server=ANDREW-PC\\SQLEXPRESS;Database=TestSNMPDatabase;Trusted_Connection=true;MultipleActiveResultSets=True";
                        conn.Open();

                        // Parse SNMP Version 1 TRAP packet
                        SnmpV1TrapPacket pkt = new SnmpV1TrapPacket();
                        pkt.decode(indata, inlen);

                        Console.WriteLine("community=" + pkt.Community);
                        Console.WriteLine("enterprise=" + pkt.Pdu.Enterprise);
                        Console.WriteLine("enterprise_mib_name=");
                        Console.WriteLine("uptime=" + pkt.Pdu.TimeStamp.ToString());
                        Console.WriteLine("agent_ip=" + pkt.Pdu.AgentAddress.ToString());
                        Console.WriteLine("generic_num=" + pkt.Pdu.Generic);
                        Console.WriteLine("specific_num=" + pkt.Pdu.Specific);
                        Console.WriteLine("version=" + pkt.Version);
                        Console.WriteLine("generic_name=" + GenericName(pkt.Pdu.Generic));
                        Console.WriteLine("type=" + pkt.Pdu.Type);

                        string        rawMessage          = "";
                        string        friendlyMessage     = "";
                        List <string> messages            = new List <string>();
                        List <string> friendlyMessageList = new List <string>();
                        string[]      Oidtables           = { "OidTable" };
                        string[]      MIBtables           = { "EnterpriseMibName" };
                        string        enterprise_num      = pkt.Pdu.Enterprise.ToString().Split('.')[6];
                        string        mibName             = ReadMIBTables(MIBtables, conn, enterprise_num);
                        bool          first     = true;
                        int           ignoreVal = 0;

                        foreach (Vb v in pkt.Pdu.VbList)
                        {
                            int varValue = Int32.Parse(v.Oid.ToString().Split('.').Last());
                            Console.WriteLine("**** {0} {1}: {2}", v.Oid.ToString(), SnmpConstants.GetTypeName(v.Value.Type), v.Value.ToString());
                            messages.Add("var" + varValue.ToString("D2") + "_oid=" + v.Oid);
                            messages.Add("var" + varValue.ToString("D2") + "_value=" + v.Value.ToString());
                            if (ReadOidTables(Oidtables, conn, v.Oid.ToString()))
                            {
                                friendlyMessageList.Add("var" + varValue.ToString("D2") + "_oid=" + v.Oid);
                                friendlyMessageList.Add("var" + varValue.ToString("D2") + "_value=" + v.Value.ToString());
                            }
                            //check first OID in ignore table
                            if (first)
                            {
                                ignoreVal = CheckIgnore(Oidtables, conn, v.Oid.ToString());
                                first     = false;
                            }
                        }
                        rawMessage      = string.Join(",", messages);
                        friendlyMessage = string.Join(",", friendlyMessageList);
                        Console.WriteLine("Friendly message: " + friendlyMessage);

                        string sql = "INSERT INTO SNMPTable ([SNMP version],Community,[Enterprise OID],enterprise_mib_name," +
                                     "[Agent IP],[Generic Number],[Friendly Message],[Raw Message],Timestamp,Ignore) " +
                                     "VALUES (@0, @1, @2, @3, @4, @5, @6, @7, @8, @9)";
                        SqlCommand insertCommand = new SqlCommand(sql, conn);
                        int        max           = 8000; //max length of varchar in sql server
                        insertCommand.Parameters.Add("@0", SqlDbType.VarChar, max).Value = pkt.Version.ToString();
                        insertCommand.Parameters.Add("@1", SqlDbType.VarChar, max).Value = pkt.Community.ToString();
                        insertCommand.Parameters.Add("@2", SqlDbType.VarChar, max).Value = pkt.Pdu.Enterprise.ToString();
                        insertCommand.Parameters.Add("@3", SqlDbType.VarChar, max).Value = mibName;
                        insertCommand.Parameters.Add("@4", SqlDbType.VarChar, max).Value = pkt.Pdu.AgentAddress.ToString();
                        insertCommand.Parameters.Add("@5", SqlDbType.VarChar, max).Value = pkt.Pdu.Generic.ToString();
                        insertCommand.Parameters.Add("@6", SqlDbType.VarChar, max).Value = friendlyMessage;
                        insertCommand.Parameters.Add("@7", SqlDbType.VarChar, max).Value = rawMessage;
                        insertCommand.Parameters.Add("@8", SqlDbType.VarChar, max).Value = DateTime.Now.ToString("yyyyMMdd h:mm:ss tt");
                        insertCommand.Parameters.Add("@9", SqlDbType.Int).Value          = ignoreVal;
                        insertCommand.ExecuteNonQuery();
                        conn.Close();
                        Console.WriteLine("** End of SNMP Version 1 TRAP data.");
                    }
                }
                else
                {
                    if (inlen == 0)
                    {
                        Console.WriteLine("Zero length packet received.");
                    }
                }
            }
        }
Пример #8
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.");
                }
            }
        }
Пример #9
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.");
                    }
                }
            }
        }
Пример #10
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");
    }
Пример #11
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, "");
                            }
                        }
                    }
                }
            }
        }