Proper way to scan a range of IP addresses

Josh G picture Josh G · Nov 17, 2009 · Viewed 10.8k times · Source

Given a range of IP addresses entered by a user (through various means), I want to identify which of these machines have software running that I can talk to.

Here's the basic process:

  1. Ping these addresses to find available machines

  2. Connect to a known socket on the available machines

  3. Send a message to the successfully established sockets

  4. Compare the response to the expected response

Steps 2-4 are straight forward for me. What is the best way to implement the first step in .NET?

I'm looking at the System.Net.NetworkInformation.Ping class. Should I ping multiple addresses simultaneously to speed up the process? If I ping one address at a time with a long timeout it could take forever. But with a small timeout, I may miss some machines that are available.

Sometimes pings appear to be failing even when I know that the address points to an active machine. Do I need to ping twice in the event of the request getting discarded?

To top it all off, when I scan large collections of addresses with the network cable unplugged, Ping throws a NullReferenceException in FreeUnmanagedResources(). !?

Any pointers on the best approach to scanning a range of IPs like this?

Answer

Yoopergeek picture Yoopergeek · Nov 17, 2009

Don't forget the headache of the people who will deny pinging in their firewall rules.

My only suggestion is perhaps a question: Do you have to do #1?

Can't you simply try to connect to that known socket? Successful connection to that socket kills two birds with one stone: yes the host is there/alive, and yes, the known-socket is open.

This type of situation does lend itself well to multithreading, fire it off on another thread, and wait for it to come back with an answer...