Example #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}");
                    }
                }
            });
        }
Example #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线程结束");
        }
Example #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)
                            {
                            }
                        }
                    }
                }
            }
        }
Example #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);
        }
Example #5
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);
        }
Example #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.");
                    }
                }
            }
        }
Example #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.");
                    }
                }
            }
        }
Example #8
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.");
                    }
                }
            }
        }
Example #9
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.");
                }
            }
        }
Example #10
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.");
                    }
                }
            }
        }
Example #11
0
        public SnmpVersionOne(SnmpV1TrapPacket pkt, EndPoint inep, List <MibTreeInformation> mibTreeInformation, List <TowerDevices> towerDevices, List <AlarmLogStatus> alarmLog)
        {
            var context = GlobalHost.ConnectionManager.GetHubContext <HubMessage>();

            foreach (Vb v in pkt.Pdu.VbList)
            {
                Trap   trap = new Trap();
                string IP   = inep.ToString();
                trap.IpAddres     = pkt.Pdu.AgentAddress.ToString();
                trap.CurrentOID   = pkt.Pdu.Enterprise.ToString();
                trap.ReturnedOID  = v.Oid.ToString();
                trap.dateTimeTrap = DateTime.Now.ToString();

                if (v.Value.GetType().Name == "OctetString")
                {
                    trap.Value = hex.Hexstrings(v.Value.ToString());
                }
                else
                {
                    trap.Value = v.Value.ToString();
                }
                var tDevice = towerDevices.Where(t => t.IP == pkt.Pdu.AgentAddress.ToString()).FirstOrDefault();

                alarmStatusDescription = alarmstatus.AlarmColorDefines(trap.Value, trap.CurrentOID, trap.ReturnedOID, alarmLog, tDevice);
                trap.AlarmStatus       = alarmStatusDescription.AlarmStatusColor;
                trap.AlarmDescription  = alarmStatusDescription.AlarmDescription;

                if (tDevice == null)
                {
                    trap.Countrie    = "Unknown";
                    trap.States      = "Unknown";
                    trap.City        = "Unknown";
                    trap.DeviceName  = "Unknown";
                    trap.TowerName   = "Unknown";
                    trap.Description = "Unknown";
                }
                else
                {
                    trap.Countrie   = tDevice.CountrieName;
                    trap.States     = tDevice.StateName;
                    trap.City       = tDevice.CityName;
                    trap.DeviceName = tDevice.DeviceName;
                    trap.TowerName  = tDevice.TowerName;

                    string oid = pkt.Pdu.Enterprise.ToString();
                    var    OidMibdescription = mibTreeInformation.Where(o => o.OID == oid).FirstOrDefault();
                    if (OidMibdescription == null)
                    {
                        oid = oid.Remove(oid.Length - 1);
                        oid = oid.Remove(oid.Length - 1);
                        OidMibdescription = mibTreeInformation.Where(o => o.OID == oid).FirstOrDefault();
                    }
                    if (OidMibdescription == null)
                    {
                        oid = oid.Remove(oid.Length - 1);
                        oid = oid.Remove(oid.Length - 1);
                        OidMibdescription = mibTreeInformation.Where(o => o.OID == oid).FirstOrDefault();

                        if (OidMibdescription != null)
                        {
                            trap.Description = OidMibdescription.Description;
                            trap.OIDName     = OidMibdescription.Name;
                        }
                        else
                        {
                            trap.Description = "Unknown";
                            trap.OIDName     = "Unknown";
                        }
                    }
                    else
                    {
                        if (OidMibdescription.Description != null)
                        {
                            trap.Description = OidMibdescription.Description;
                        }
                        trap.OIDName = OidMibdescription.Name;
                    }
                    if (trap.Description == "")
                    {
                        trap.Description = "Unknown";
                    }
                }
                context.Clients.All.onHitRecorded(trap);

                db.Traps.Add(trap);
                db.SaveChanges();
            }
        }
Example #12
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");
    }
Example #13
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, "");
                            }
                        }
                    }
                }
            }
        }