Click here to Skip to main content
12,548,514 members (52,811 online)
Click here to Skip to main content
Add your own
alternative version


21 bookmarked

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

, 23 Mar 2015 CPOL
Rate this:
Please Sign up or sign in to vote.
Info:Devices IP,MAC,HostName


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.


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:

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().

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()
                System.Net.NetworkInformation.Ping ping = new System.Net.NetworkInformation.Ping();
                ping.PingCompleted += new PingCompletedEventHandler(PingCompleted);
                ping.SendAsync(host, timeout, host);
                // 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.

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

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);

               // 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.

public string GetHostName(string ipAddress)
                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;
            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;

                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.

private void Form1_Load(object sender, EventArgs e)

            lstLocal.View = View.Details;
            lstLocal.GridLines = true;
            lstLocal.FullRowSelect = true;
            lstLocal.BackColor = System.Drawing.Color.Aquamarine;
            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.


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


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


About the Author

Jeddi khan
Pakistan Pakistan
No Biography provided

You may also be interested in...


Comments and Discussions

QuestionIt works fine Pin
Member 1223721917-Jul-16 6:03
memberMember 1223721917-Jul-16 6:03 
AnswerRe: It works fine Pin
Member 1223721917-Jul-16 20:44
memberMember 1223721917-Jul-16 20:44 
GeneralMy vote of 1 Pin
Member 1153189223-Jun-16 10:45
memberMember 1153189223-Jun-16 10:45 
QuestionAdapter Company Name Pin
Hakki UN19-Jun-16 12:23
memberHakki UN19-Jun-16 12:23 
QuestionIndexOutOfRange Exception Pin
Sea Zhen Bin28-Feb-16 21:05
memberSea Zhen Bin28-Feb-16 21:05 
AnswerRe: IndexOutOfRange Exception Pin
Member 1280530120-Oct-16 4:58
memberMember 1280530120-Oct-16 4:58 
Questionquestion Pin
Gharibe Jon20-Sep-15 6:07
memberGharibe Jon20-Sep-15 6:07 
GeneralMy vote of 3 Pin
Ashish Jain(Be Jovial)9-Aug-15 8:17
memberAshish Jain(Be Jovial)9-Aug-15 8:17 
Questionwhat is invokerequired ?! Pin
Member 1185140724-Jul-15 22:55
memberMember 1185140724-Jul-15 22:55 
QuestionMessage Removed Pin
Member 1185140720-Jul-15 23:37
memberMember 1185140720-Jul-15 23:37 
QuestionDuplicate entries Pin
Member 96523377-Jun-15 7:23
memberMember 96523377-Jun-15 7:23 
AnswerRe: Duplicate entries Pin
Jeddi khan16-Jun-15 17:54
memberJeddi khan16-Jun-15 17:54 
AnswerRe: Duplicate entries Pin
Member 1223721917-Jul-16 18:41
memberMember 1223721917-Jul-16 18:41 
QuestionNice Article! Pin
Mr. Javaman27-Mar-15 2:14
memberMr. Javaman27-Mar-15 2:14 
AnswerRe: Nice Article! Pin
Jeddi khan28-Mar-15 3:19
memberJeddi khan28-Mar-15 3:19 
QuestionAre you assuming the subnet mask is Pin
yxhu27-Mar-15 1:11
memberyxhu27-Mar-15 1:11 
AnswerRe: Are you assuming the subnet mask is Pin
Jeddi khan28-Mar-15 3:18
memberJeddi khan28-Mar-15 3:18 
GeneralIt works Pin
FarmpartnerTec25-Mar-15 0:04
memberFarmpartnerTec25-Mar-15 0:04 
GeneralRe: It works Pin
Jeddi khan25-Mar-15 0:38
memberJeddi khan25-Mar-15 0:38 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.161021.1 | Last Updated 23 Mar 2015
Article Copyright 2015 by Jeddi khan
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid