HavocXphere
Honorary Master
I'm toying around with some code, most of which I got off MSDN over here.
Pings 256 IPs on a local LAN, 3 of which should respond.
The code works largely as expected, but a couple of things are bothering me about it:
Thanks
Pings 256 IPs on a local LAN, 3 of which should respond.
The code works largely as expected, but a couple of things are bothering me about it:
- It seems slow to me. 2 minutes to run through 256 IPs. Is that normal?
- The timeout value has no effect on the time taken. I think the time taken should drop if I reduce the timeout.
- [-]The IDE shows a warning for the exception handling I'm doing (variable e unused). Is there a more correct way to ignore exceptions (Ping accepts hostnames too & bombs if it can't resolve them)?[/-]
- [-]Is this something one would use threading for to make it more async?[/-]
Thanks
Code:
public static bool PingIP(string ip)
{
bool outcome = false;
Ping pingSender = new Ping();
PingOptions options = new PingOptions();
// Use the default Ttl value which is 128,
// but change the fragmentation behavior.
options.DontFragment = true;
// Create a buffer of 32 bytes of data to be transmitted.
string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
byte[] buffer = Encoding.ASCII.GetBytes(data);
int timeout = 120;
try
{
PingReply reply = pingSender.Send(ip, timeout, buffer, options);
if (reply.Status == IPStatus.Success)
{
outcome = true;
}
}
catch (Exception e)
{
}
return outcome;
}
public void PingNow()
{
int tickstart = Environment.TickCount;
for (int i = 0; i < 256; i++)
{
if (PingIP("192.168.0." + i))
{
//LB.Items.Add("192.168.0." + i +" succeeded");
}
else
{
//LB.Items.Add("192.168.0." + i + " failed");
}
}
LB.Items.Add("Done: " + (Environment.TickCount - tickstart));
}
Last edited: