Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#5.0

How to List all devices info on your WLAN /router Programmatically in C#

4.09/5 (16 votes)
23 Mar 2015CPOL3 min read 116K  
Info:Devices IP,MAC,HostName

Introduction

While writing an app for my Company,i needed a code to scan all devices on my WLAN .I did an effort googling to help but all in vain.I was told to use WNET Watcher and  Wifi Manager/Advanced Wifi Manager and some other tools..Like you , i had to write it in simple C# as a part of Project.

Background

Basically,it requires PING class.You have to Ping all devices on your WLAN.The Ping sends ICMP control message 4bytes in length.If the other device on your network respond with-in  time-out(pre-defined by you) you're lucky. But how would you know where to start Pinging?You may manually find your IP Address typing IPCONFIG/ALL on cmd.exe and then incrementing the last numeral to get the active devices list.But this is a rather tedious and cumbersome job while we're having a simple method with having three arguments.Oh!,Hold-on i am telling it verbally but you need it programmatically.Brace your self we'll be having it shortly.

The Ping() class is troublesome on other hand ,if you use Ping.Send() instead of Ping.SendAsync() you may run in the probelm of Blue Screen On Display(BSOD) with a bug-check code 0x76, PROCESS_HAS_LOCKED_PAGES in tcpip.sys .This is a serious bug in win7 and win8 as well ,reported here.I once found it while (Ping)ing all devices with a pre-defined sleep() duration.So,you may face it in one way or another but the only solution i found is using SendAsync() or mulit-threading().

Using the code

First you have to find your NetworkGateway IP using the following method:

C#
static string NetworkGateway()
{
    string ip = null;

    foreach (NetworkInterface f in NetworkInterface.GetAllNetworkInterfaces())
    {
        if (f.OperationalStatus == OperationalStatus.Up)
        {
            foreach (GatewayIPAddressInformation d in f.GetIPProperties().GatewayAddresses)
            {
                ip = d.Address.ToString();
            }
        }
    }

    return ip;
}

The NetworkInterface.GetAllNetworkInterfaces() method would provide you the list of all Network adapters which is a key factor for your computer connectivity to the network.This is quite a simple step .Infact,it avoided you to open cmd.exe and find it manually.

How to find other IP's is still unclear.Right? 

Simple:Just get the last octet of  ip by splitting it and increment it as you did manually upto 255(total no.of IP Addresses).Ping them one-by-one unitl you're tired,definitely your PC! .But you should mind it,the more you allocate time-out ,the more will be response time,the better the Listings.

To avoid blocking and possible BSOD ,here is the full procedure to call Ping() using SendAsync().

C#
public void Ping_all()
        {

            string gate_ip = NetworkGateway();
           
            //Extracting and pinging all other ip's.
            string[] array = gate_ip.Split('.');

            for (int i = 2; i <= 255; i++)
            {  
                
                string ping_var = array[0] + "." + array[1] + "." + array[2] + "." + i;   

                //time in milliseconds           
                Ping(ping_var, 4, 4000);

            }          
            
        }    

public void Ping(string host, int attempts, int timeout)
{
   for (int i = 0; i < attempts; i++)
    {
        new Thread(delegate()
        {
            try
            {
                System.Net.NetworkInformation.Ping ping = new System.Net.NetworkInformation.Ping();
                ping.PingCompleted += new PingCompletedEventHandler(PingCompleted);
                ping.SendAsync(host, timeout, host);
            }
            catch
            {
                // Do nothing and let it try again until the attempts are exausted.
                // Exceptions are thrown for normal ping failurs like address lookup
                // failed.  For this reason we are supressing errors.
            }
        }).Start();
    }
}
 

You shouldn't forget to handle every ping response using an EventHandler

C#
private void PingCompleted(object sender, PingCompletedEventArgs e)
        {
            string ip = (string)e.UserState;
            if (e.Reply != null && e.Reply.Status == IPStatus.Success)
            {
                string hostname=GetHostName(ip);
                string macaddres=GetMacAddress(ip);
                string[] arr = new string[3];
                
                //store all three parameters to be shown on ListView
                arr[0] = ip;
                arr[1] = hostname;
                arr[2] = macaddres;

                // Logic for Ping Reply Success
                ListViewItem item;
                if (this.InvokeRequired)
                {
                    
                    this.Invoke(new Action(() =>
                    {
                        
                        item = new ListViewItem(arr);
                      
                            lstLocal.Items.Add(item);
                         
                        
                    }));
                }
              

            }
            else
            {
               // MessageBox.Show(e.Reply.Status.ToString());
            }
        }
    
 

Did u saw GetHostName and GetMacAddress()? They are there to aid you in getting these info's which otherwise wouldn't be possible without IP. Also,lstLocal is the name of ListView item where you'd display Network info.on the Form,which i would tell you shortly.

Both of the methods below are self-explanatory.

C#
public string GetHostName(string ipAddress)
        {
            try
            {
                IPHostEntry entry = Dns.GetHostEntry(ipAddress);
                if (entry!= null)
                {
                    return entry.HostName;
                }
            }
            catch (SocketException)
            {
               // MessageBox.Show(e.Message.ToString());
            }

            return null;
       }


        //Get MAC address
public string GetMacAddress(string ipAddress)
        {
            string macAddress = string.Empty;
            System.Diagnostics.Process Process = new System.Diagnostics.Process();
            Process.StartInfo.FileName = "arp";
            Process.StartInfo.Arguments = "-a " + ipAddress;
            Process.StartInfo.UseShellExecute = false;
            Process.StartInfo.RedirectStandardOutput = true;
            Process.StartInfo.CreateNoWindow = true;
            Process.Start();
            string strOutput = Process.StandardOutput.ReadToEnd();
            string[] substrings = strOutput.Split('-');
            if (substrings.Length >= 8)
            {
                macAddress = substrings[3].Substring(Math.Max(0, substrings[3].Length - 2))
                         + "-" + substrings[4] + "-" + substrings[5] + "-" + substrings[6]
                         + "-" + substrings[7] + "-"
                         + substrings[8].Substring(0, 2);
                return macAddress;
            }

            else
            {
                return "OWN Machine";
            }
        }    

Now some words on how would you get these methods working:

Create a Winform application and drag ListView upon it,re-name it to lstLocal.Add the following code to your Form1_Load() and you're done.

C#
private void Form1_Load(object sender, EventArgs e)
   {

            lstLocal.View = View.Details;
            lstLocal.Clear();
            lstLocal.GridLines = true;
            lstLocal.FullRowSelect = true;
            lstLocal.BackColor = System.Drawing.Color.Aquamarine;
            lstLocal.Columns.Add("IP",100);
            lstLocal.Columns.Add("HostName", 200);
            lstLocal.Columns.Add("MAC Address",300);
            lstLocal.Sorting = SortOrder.Descending;
            Ping_all();   //Automate pending
          

   }
 

Points of Interest

Meanwhile,this is just a slice of my project.Enjoy it! I'd be painting the other half i.e.File Sharing on WLAN in the near future.

History

Keep a running update of any changes or improvements you've made here.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)