This blog has, IMO, some great resources. Unfortunately, some of those resources are becoming less relevant. I'm still blogging, learning tech and helping others...please find me at my new home on http://www.jameschambers.com/.

Tuesday, April 28, 2009

Ping! You’re It!

Here’s a quick little bit of code that will allow you to scan a subnet for available IP addresses (provided no one is blocking ICMP traffic).

You’ll need to add a reference to System.Windows.Forms to allow access to the clipboard (and mark your entry method with [STAThread].

The formatting’s terrible, but I just copy & pasted and it worked…

namespace Spike.IMCP
{
class Program
{
[STAThread]
static void Main(string[] args)
{
Ping pingSender = new Ping();
List<string> available = new List<string>();
List<string> unavailable = new List<string>();

for (int i = 1; i < 255; i++)
{
string address = string.Format("192.168.0.{0}", i);
PingReply reply = pingSender.Send(address,20);
switch (reply.Status)
{
case IPStatus.Success:
Console.WriteLine("{0} {1}ms TTL:{2}", reply.Address.ToString(), reply.RoundtripTime, "");
available.Add(address);
break;
default:
//Console.WriteLine("{0} ({1})", reply.Status, address);
unavailable.Add(address);
break;
}


}

Console.WriteLine("Unavailable addresses");
StringBuilder sb = new StringBuilder();

foreach (string item in unavailable)
{
Console.WriteLine(" {0}", item);
sb.AppendLine(item);
}

Clipboard.SetText(sb.ToString());

Console.ReadLine();

}
}
}

No comments:

Post a Comment