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..L
ike 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:
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();
string[] array = gate_ip.Split('.');
for (int i = 2; i <= 255; i++)
{
string ping_var = array[0] + "." + array[1] + "." + array[2] + "." + i;
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
{
}
}).Start();
}
}
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];
arr[0] = ip;
arr[1] = hostname;
arr[2] = macaddres;
ListViewItem item;
if (this.InvokeRequired)
{
this.Invoke(new Action(() =>
{
item = new ListViewItem(arr);
lstLocal.Items.Add(item);
}));
}
}
else
{
}
}
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)
{
try
{
IPHostEntry entry = Dns.GetHostEntry(ipAddress);
if (entry!= null)
{
return entry.HostName;
}
}
catch (SocketException)
{
}
return null;
}
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.
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();
}
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.