Click here to Skip to main content
14,608,080 members

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

Rate this:
4.00 (15 votes)
Please Sign up or sign in to vote.
4.00 (15 votes)
23 Mar 2015CPOL
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

Comments and Discussions

QuestionGot only Info of my Device Pin
Member 1407312730-Nov-18 8:32
MemberMember 1407312730-Nov-18 8:32 
QuestionGalaxy J7-2016 problem Pin
Member 104109728-Jun-18 7:08
MemberMember 104109728-Jun-18 7:08 
QuestionNice work Pin
Member 104109723-Jun-18 19:32
MemberMember 104109723-Jun-18 19:32 
Suggestionipv6 problem... Pin
Member 1295279729-Dec-17 7:55
MemberMember 1295279729-Dec-17 7:55 
QuestionThanks Pin
rasool200721-Aug-17 2:51
Memberrasool200721-Aug-17 2:51 
Questionthe code don't work??? Pin
Member 1210541020-Jun-17 15:25
MemberMember 1210541020-Jun-17 15:25 
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 
AnswerRe: what is invokerequired ?! Pin
Member 1385277631-May-18 0:33
MemberMember 1385277631-May-18 0:33 
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 
GeneralRe: Duplicate entries Pin
kariyamvinod24-Oct-19 3:51
Memberkariyamvinod24-Oct-19 3:51 
QuestionNice Article! Pin
Mr. Angular27-Mar-15 2:14
MemberMr. Angular27-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 

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.

Posted 23 Mar 2015


31 bookmarked