Windows Forms: How to scan IP address in a network using C#

This post shows you How to scan IP address in a network using C# Windows Forms Application.

Sometimes you need to check network information such as status, hosname of an ip range in LAN, the following article will guide you on how to do this.

C# local network discovery

Dragging ListView, TextBox, Label, ProgressBar and Button controls from the Visual Studio toolbox into your form designer, then design a simple UI allows you to implement a basic IP Scanner to explore the local network as shown below.

c# network scanner

This is a simple c# ip scanner allows you to scan ip range in a subnet network. Using c# network discovery, you can easily get hostname, status infromation from specific ip address.

Adding a click event handler to the Scan button allows you to scan subnet ip address in local network.

C# network scanner

//get ip address of all computers on network c#
private void btnScan_Click(object sender, EventArgs e)
{
    string subnet = txtSubnet.Text;
    progressBar.Maximum = 254;
    progressBar.Value = 0;
    lvResult.Items.Clear();

    Task.Factory.StartNew(new Action(() =>
    {
        for (int i = 2; i < 255; i++)
        {
            string ip = $"{subnet}.{i}";
            Ping ping = new Ping();
            PingReply reply = ping.Send(ip, 100);
            if (reply.Status == IPStatus.Success)
            {
                progressBar.BeginInvoke(new Action(() =>
                {
                    try
                    {
                        IPHostEntry host = Dns.GetHostEntry(IPAddress.Parse(ip));
                        lvResult.Items.Add(new ListViewItem(new String[] { ip, host.HostName, "Up" }));
                    }
                    catch
                    {
                        MessageBox.Show($"Couldn't retrieve hostname from {ip}", "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    progressBar.Value += 1;
                    lblStatus.ForeColor = Color.Blue;
                    lblStatus.Text = $"Scanning: {ip}";
                    if (progressBar.Value == 253)
                        lblStatus.Text = "Finished";
                }));
            }
            else
            {
                progressBar.BeginInvoke(new Action(() =>
                {
                    progressBar.Value += 1;
                    lblStatus.ForeColor = Color.DarkGray;
                    lblStatus.Text = $"Scanning: {ip}";
                    lvResult.Items.Add(new ListViewItem(new String[] { ip, "", "Down" }));
                    if (progressBar.Value == 253)
                        lblStatus.Text = "Finished";
                }));
            }
        }
    }));
}

Through this c# example, i showed you how to get all ip address on a lan network in c#. You can easily scan all IPs and computer's names from LAN network using c# windows forms application.

Related