Network segment address scanning (single-thread, multi-thread, multi-task)

Added the time to scan each IP address, and the total time to scan.

using System;
using System.Collections.Generic;
using System. Diagnostics;
using System. Linq;
using System.Net;
using System. Text;
using System. Threading;
using System. Threading. Tasks;
using System. Windows;
using System. Windows. Controls;
using System. Windows. Data;
using System. Windows. Documents;
using System. Windows. Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System. Windows. Navigation;
using System. Windows. Shapes;

namespace WpfApp1
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            LabelError.Visibility = System.Windows.Visibility.Collapsed;
        }

        private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
        {
             
            if (txtStart == null || txtEnd == null || ButtonScan1 == null )
            {
                return;
            }
            try
            {
                start = int. Parse(txtStart. Text);
                end = int. Parse(txtEnd. Text);
            }catch(Exception ex)
            {
                this.LabelError.Visibility = System.Windows.Visibility.Visible;
                this.ButtonScan1.IsEnabled = false;
                this.ButtonScan2.IsEnabled = false;
                this.ButtonScan3.IsEnabled = false;
                return;
            }
             
            //ip acquisition
            string strIP1 = txtPrefix.Text + txtStart.Text;
            string strIP2 = txtPrefix.Text + txtEnd.Text;
            
            IP Address ip1, ip2;
            if (IPAddress. TryParse(strIP1, out ip1) == false || IPAddress. TryParse(strIP2, out ip2) == false|| start > end )
            {
                this.LabelError.Visibility = System.Windows.Visibility.Visible;
                this.ButtonScan1.IsEnabled = false;
                this.ButtonScan2.IsEnabled = false;
                this.ButtonScan3.IsEnabled = false;
                return;
            }
            else
            {
                ButtonScan1. IsEnabled = true;
                ButtonScan2. IsEnabled = true;
                ButtonScan3. IsEnabled = true;
                LabelError.Visibility = System.Windows.Visibility.Collapsed;
            }
        }
        Stopwatch w2;
        int cout;
        int start;
        int end;
        private void ButtonScan_Click1(object sender, RoutedEventArgs e)
        {
            judge();
            cout = 0;
            start = int. Parse(txtStart. Text);
            end = int. Parse(txtEnd. Text);
            this.listBoxResult.Items.Clear();
            Thread t1 = new Thread(Time);
            t1. Start();
            w2 = Stopwatch. StartNew();
            for (int i = start; i <= end; i ++ )
            {
                //192.168.1.+i
                string strip = this.txtPrefix.Text + i;
                Thread t = new Thread(Scan);
                t.Start(strip);
            }
            
        }
        private void ButtonScan_Click2(object sender, RoutedEventArgs e)
        {
            judge();
            start = int. Parse(txtStart. Text);
            end = int. Parse(txtEnd. Text);
            this.listBoxResult.Items.Clear();
            Stopwatch w3 = Stopwatch. StartNew();
            for (int i = start; i <= end; i ++ )
            {
                Stopwatch w1 = Stopwatch.StartNew();//timer
                string strip = this.txtPrefix.Text + i;
                string strHost;
                try
                {
                    strHost = Dns.GetHostEntry(strip).HostName;
                }
                catch (Exception ex)
                {
                    strHost = "Not online!";
                }
                w1. Stop();
                this.listBoxResult.Items.Add(
                    string.Format("Scan address: {0}, host DNS name: {1}, scan time: {2}",
                    strip,
                    strHost,
                    w1. ElapsedMilliseconds
                    ));
            }
            w3.Stop();
            this.listBoxResult.Dispatcher.Invoke(
                                () => listBoxResult.Items.Add(
                                      string.Format("Total time: {0} milliseconds", w3.ElapsedMilliseconds
                                      )
                             ));


        }
        private async void ButtonScan3_Click(object sender, RoutedEventArgs e)
        {
            judge();
            start = int. Parse(txtStart. Text);
            end = int. Parse(txtEnd. Text);
            this.listBoxResult.Items.Clear();
            w2 = Stopwatch. StartNew();
            Task[] tasks = new Task[end - start + 1];

            for (int i = start; i <= end; i ++ )
            {
                IPAddress ip = IPAddress. Parse(txtPrefix. Text + i);
                tasks[i - start] = Task.Run(() => Scan(ip));
            }
            for (int i = 0; i <= end - start; i ++ )
            {
                await tasks[i];

            }
            Time1();
        }
        private void Scan(Object ip)
        {
            Stopwatch w = Stopwatch. StartNew();
            string host = "";
            try
            {
                host = Dns.GetHostEntry(ip.ToString()).HostName;
            }
            catch
            {
                host = "(not online)";
            }
            w.Stop();

            this.listBoxResult.Dispatcher.Invoke(
                () => listBoxResult.Items.Add(
                      string.Format("Scan address: {0}, scan time: {1} milliseconds, host DNS name: {2} ",
                      ip, w.ElapsedMilliseconds, host)
             ));
            lock (this)
            {
                cout + + ;
            }
        }
        public void judge()
        {
            start = int. Parse(txtStart. Text);
            end = int. Parse(txtEnd. Text);
                if (start > end)
                {
                    MessageBox.Show("The end value must be greater than or equal to the start value", "The address range is wrong");
                    return;
                }
        }
        
        private void Time()
        {
                while (true)
                {
                     if (cout == end-start + 1)
                     {
                        w2.Stop();
                    this.listBoxResult.Dispatcher.Invoke(
                                     () => listBoxResult.Items.Add(
                                           string.Format("Total time: {0} milliseconds", w2.ElapsedMilliseconds
                                           )
                                  ));
                        return;
                     }
                }
        }
        /// <summary>
        /// Single IP resolution
        /// </summary>
        /// <param name="strip">ip address</param>
        /// <returns>hostname</returns>
       
        private void Time1()
        {
            while (true)
            {
                    w2.Stop();
                    this.listBoxResult.Dispatcher.Invoke(
                                     () => listBoxResult.Items.Add(
                                           string.Format("Total time: {0} milliseconds", w2.ElapsedMilliseconds
                                           )
                                  ));
                    return;
            }
        }
    }
}
<Window x:Class="WpfApp1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApp1"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <Grid. RowDefinitions>
            <RowDefinition Height="Auto"></RowDefinition>
            <RowDefinition Height="Auto"></RowDefinition>
            <RowDefinition></RowDefinition>
        </Grid. RowDefinitions>
        <GroupBox Grid.Row="0" Header="Scan IP address">
            <DockPanel>
                <Label Content="Address Prefix" />
                <TextBox x:Name="txtPrefix" Text="192.168.1." Width="100" Margin="0,0,10,0" Height="20" TextChanged= "TextBox_TextChanged" />
                <Label Content="Start Value:" Margin="10,0,0,0" />
                <TextBox x:Name="txtStart" Text="1" Width="50" Height="20" TextChanged="TextBox_TextChanged" />
                <Label Content="End value:" Margin="10,0,0,0" />
                <TextBox x:Name="txtEnd" Text="10" Width="50" Height="20" TextChanged="TextBox_TextChanged"/>
                <Button x:Name="ButtonScan1" Content="Multi-thread Scanning" Width="100" Click="ButtonScan_Click1" Height="20" Margin="5,2" />
                <Button x:Name="ButtonScan2" Content="Single Thread Scan" Width="100" Click="ButtonScan_Click2" Height="20" Margin="1,2" HorizontalAlignment="Left"/>
                <Button x:Name="ButtonScan3" Content="Multi-tasking scan" Width="100" Click="ButtonScan3_Click" Height="20" Margin="1,2" HorizontalAlignment="Left"/>

            </DockPanel>
        </GroupBox>
        <Label Grid.Row="1" Name="LabelError" Background="red" Content="Wrong IP address" HorizontalContentAlignment="Center" />
        <GroupBox Header="Scan Information" Grid.Row="2">
            <ListBox x:Name="listBoxResult"/>
        </GroupBox>
    </Grid>
</Window>

Some things that could be improved:

  • Filling in the IP address does not meet the requirements when end>start, but a judge method is called here to judge whether it meets the requirements. I want to pop up a red prompt as if the input IP address does not comply with the rules. After trying it, there are some problems. When the filled IP is empty, an error will be reported directly.
  • There seems to be some problems with the total time of multitasking. When I scan more addresses, the total time will be much longer. I think it is the point of await, traversal and waiting, even if some scans are completed, it will still judge the time spent.

————————- Some knowledge points are too lazy to write, and I will update when I want to write —— ———————-