コード例 #1
0
        private void Discover()
        {
            DiscoveredDevices.Clear();
            txbDiscoveryOutput.Text = "";

            string[] ipStartParts = txbDiscoveryStart.Text.Split('.');
            string[] ipEndParts   = txbDiscoveryEnd.Text.Split('.');

            int deviceCount     = 0;
            int progressCounter = 0;

            int rangeSize = Convert.ToInt32(ipEndParts[3]) - Convert.ToInt32(ipStartParts[3]);

            bgwDiscovery.ReportProgress(-rangeSize);
            bgwDiscovery.ReportProgress(0);

            if (chbPingCheck.Checked)
            {
                rangeSize *= 2;
                bgwDiscovery.ReportProgress(-rangeSize);
                bgwDiscovery.ReportProgress(0);

                bgwDiscovery.ReportProgress(2000000);

                for (int i = Convert.ToInt32(ipStartParts[3]); i <= Convert.ToInt32(ipEndParts[3]); i++)
                {
                    string currentIP = ipStartParts[0] + "." + ipStartParts[1] + "." + ipStartParts[2] + "." + i.ToString();

                    if (bgwDiscovery.CancellationPending)
                    {
                        return;
                    }

                    try
                    {
                        Ping ping = new Ping();
                        ping.Send(currentIP, 500);

                        FoundIPAtPercentage.Add(progressCounter, new Tuple <string, string>(currentIP, ""));
                        bgwDiscovery.ReportProgress(5000000 + progressCounter);
                    }
                    catch (Exception)
                    { }

                    bgwDiscovery.ReportProgress(progressCounter++);
                }
            }

            bgwDiscovery.ReportProgress(3000000);

            // Start the discovery
            for (int i = Convert.ToInt32(ipStartParts[3]); i <= Convert.ToInt32(ipEndParts[3]); i++)
            {
                if (bgwDiscovery.CancellationPending)
                {
                    return;
                }

                string currentIP  = ipStartParts[0] + "." + ipStartParts[1] + "." + ipStartParts[2] + "." + i.ToString();
                string currentMAC = NetExplore.GetMacAddress(currentIP);
                if (!string.IsNullOrEmpty(currentMAC))
                {
                    string    currentHostname = NetExplore.GetMachineNameFromIPAddress(currentIP);
                    NetDevice ntd             = new NetDevice
                    {
                        IPv4     = currentIP,
                        MAC      = currentMAC,
                        Hostname = currentHostname,
                        Name     = "Device-" + currentMAC
                    };

                    FoundIPAtPercentage.Add(progressCounter, new Tuple <string, string>(currentIP, currentHostname));
                    bgwDiscovery.ReportProgress(4000000 + progressCounter);

                    DiscoveredDevices.Add(ntd);

                    deviceCount++;
                }

                bgwDiscovery.ReportProgress(progressCounter++);
            }

            MessageBox.Show("Discovery finished!" + Environment.NewLine + $"Found a total of {DiscoveredDevices.Count} devices.", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
コード例 #2
0
        private void bgwUpdateEntries_DoWork(object sender, DoWorkEventArgs e)
        {
            Dictionary <string, bool> DevicePowerState = new Dictionary <string, bool>();

            // Get all devices, set powerstate to false
            DevicePowerState.Clear();
            sql.Open();
            using (SQLiteDataReader reader = sql.ExecuteQuery("SELECT * FROM Devices"))
                while (reader.Read())
                {
                    DevicePowerState.Add(Convert.ToString(reader["MACAddress"]), false);
                }
            sql.Close();

            Ping          ping  = new Ping();
            StringBuilder sqlSB = new StringBuilder();

            if (ipStartParts[0] == ipEndParts[0] && ipStartParts[1] == ipEndParts[1] && ipStartParts[2] == ipEndParts[2])
            {
                for (int i = Convert.ToInt32(ipStartParts[3]); i <= Convert.ToInt32(ipEndParts[3]); i++)
                {
                    if (bgwUpdateEntries.CancellationPending)
                    {
                        return;
                    }

                    bgwUpdateEntries.ReportProgress(i);

                    string    currentIP = ipStartParts[0] + "." + ipStartParts[1] + "." + ipStartParts[2] + "." + i.ToString();
                    PingReply reply     = ping.Send(currentIP, 100);

                    if (reply.Status == IPStatus.Success)
                    {
                        string currentMAC = NetExplore.GetMacAddress(currentIP);

                        if (!string.IsNullOrEmpty(currentMAC))
                        {
                            // Update the power-state of the device
                            if (DevicePowerState.ContainsKey(currentMAC))
                            {
                                // Known device, only update values
                                DevicePowerState[currentMAC] = true;
                                sqlSB.Append($"UPDATE Devices SET IP4Address = '{currentIP}', LastSeen = '{DateTime.Now:yyyy-MM-dd H:mm:ss}' WHERE MACAddress = '{currentMAC}';");
                            }
                            else
                            {
                                // New, unknown device, add to DB
                                DevicePowerState.Add(currentMAC, true);
                                sqlSB.Append($"INSERT INTO Devices (MACAddress, DeviceType, Name, IP4Address, LastSeen) VALUES ('{currentMAC}','{DeviceType.UnknownDevice}','Device-{currentMAC}','{currentIP}','{DateTime.Now:yyyy-MM-dd H:mm:ss}')");
                            }
                        }
                    }
                    else
                    {
                        continue;
                    }
                }

                if (bgwUpdateEntries.CancellationPending)
                {
                    return;
                }

                // Update IP and LastSeen, add new entries
                sql.ExecuteNonQueryACon(sqlSB.ToString());

                // Update last power-state
                StringBuilder sb = new StringBuilder();
                foreach (KeyValuePair <string, bool> entry in DevicePowerState)
                {
                    int state = 0;
                    if (entry.Value)
                    {
                        state = 1;
                    }
                    sb.Append($"UPDATE Devices SET LastPowerState = '{state}' WHERE MACAddress = '{entry.Key}';");
                }
                sql.ExecuteNonQueryACon(sb.ToString());
            }
        }
コード例 #3
0
        public static void PowerStateCheck(string pIPRangeStart, string pIPRangeEnd, BackgroundWorker pProgressReplyBGW = null)
        {
            using (WrapSQLite tsql = new WrapSQLite(SurgitManager.SurgitDatabaseLocation, true))
            {
                Dictionary <string, bool> DevicePowerState = new Dictionary <string, bool>();

                // Get all devices, set powerstate to false
                DevicePowerState.Clear();
                tsql.Open();
                using (SQLiteDataReader reader = tsql.ExecuteQuery("SELECT * FROM Devices"))
                    while (reader.Read())
                    {
                        DevicePowerState.Add(Convert.ToString(reader["MACAddress"]), false);
                    }
                tsql.Close();


                // Ping all devices in Network Range
                Ping          ping  = new Ping();
                StringBuilder sqlSB = new StringBuilder();

                if (CheckIPClassCValidity(pIPRangeStart, pIPRangeEnd))
                {
                    string[] ipStartParts = pIPRangeStart.Split('.');
                    string[] ipEndParts   = pIPRangeEnd.Split('.');

                    for (int i = Convert.ToInt32(ipStartParts[3]); i <= Convert.ToInt32(ipEndParts[3]); i++)
                    {
                        if (pProgressReplyBGW.CancellationPending)
                        {
                            return;
                        }

                        if (pProgressReplyBGW != null)
                        {
                            pProgressReplyBGW.ReportProgress(i);
                        }

                        string    currentIP = ipStartParts[0] + "." + ipStartParts[1] + "." + ipStartParts[2] + "." + i.ToString();
                        PingReply reply     = ping.Send(currentIP, 100);

                        if (reply.Status == IPStatus.Success)
                        {
                            string currentMAC = NetExplore.GetMacAddress(currentIP);

                            if (!string.IsNullOrEmpty(currentMAC))
                            {
                                // Update the power-state of the device
                                if (DevicePowerState.ContainsKey(currentMAC))
                                {
                                    // Known device, only update values
                                    DevicePowerState[currentMAC] = true;
                                    sqlSB.Append($"UPDATE Devices SET IP4Address = '{currentIP}', LastSeen = '{DateTime.Now:yyyy-MM-dd H:mm:ss}' WHERE MACAddress = '{currentMAC}';");
                                }
                                else
                                {
                                    // New, unknown device, add to DB
                                    DevicePowerState.Add(currentMAC, true);
                                    sqlSB.Append($"INSERT INTO Devices (MACAddress, DeviceType, Name, IP4Address, LastSeen) VALUES ('{currentMAC}','{DeviceType.UnknownDevice}','Device-{currentMAC}','{currentIP}','{DateTime.Now:yyyy-MM-dd H:mm:ss}')");
                                }
                            }
                        }
                        else
                        {
                            continue;
                        }
                    }

                    // Update IP and LastSeen, add new entries
                    tsql.ExecuteNonQueryACon(sqlSB.ToString());

                    // Update last power-state
                    StringBuilder sb = new StringBuilder();
                    foreach (KeyValuePair <string, bool> entry in DevicePowerState)
                    {
                        sb.Append($"UPDATE Devices SET LastPowerState = '{(entry.Value ? 1 : 0)}' WHERE MACAddress = '{entry.Key}';");
                    }
                    tsql.ExecuteNonQueryACon(sb.ToString());
                }
                else
                {
                    if (pProgressReplyBGW.CancellationPending)
                    {
                        return;
                    }
                    MessageBox.Show("The given range is not valid. Make sure the IPs are in the same subnet. Note: Only C-Class IP-Adresses are currently supported", "Invalid Range", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
            }
        }