Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class NetworkManager
- {
- private const string ipBase = "10.0.0.";
- private const bool resolveNames = true;
- private ConcurrentBag<Host> bag = new ConcurrentBag<Host>();
- private CountdownEvent countdown;
- private int upCount = 0;
- private object lockObj = new object();
- public void ping()
- {
- ping(ipBase);
- }
- public void ping(string ipBase)
- {
- countdown = new CountdownEvent(1);
- Stopwatch sw = new Stopwatch();
- sw.Start();
- for (int i = 1; i < 255; i++)
- {
- string ip = ipBase + i.ToString();
- Ping p = new Ping();
- p.PingCompleted += new PingCompletedEventHandler(p_PingCompleted);
- countdown.AddCount();
- p.SendAsync(ip, 1000, ip);
- }
- countdown.Signal();
- countdown.Wait();
- sw.Stop();
- TimeSpan span = new TimeSpan(sw.ElapsedTicks);
- Console.WriteLine("Took {0} milliseconds. {1} hosts active.", sw.ElapsedMilliseconds, upCount);
- foreach (Host h in bag)
- {
- Console.WriteLine(h.Name);
- }
- Console.ReadLine();
- }
- private void p_PingCompleted(object sender, PingCompletedEventArgs e)
- {
- string ip = (string)e.UserState;
- if (e.Reply != null && e.Reply.Status == IPStatus.Success)
- {
- if (resolveNames)
- {
- string name;
- try
- {
- IPHostEntry hostEntry = Dns.GetHostEntry(ip);
- name = hostEntry.HostName;
- }
- catch (SocketException ex)
- {
- name = "?";
- }
- Console.WriteLine("{0} ({1}) is up: ({2} ms)", ip, name, e.Reply.RoundtripTime);
- bag.Add(new Host(ip, "mac", name));
- }
- else
- {
- Console.WriteLine("{0} is up: ({1} ms)", ip, e.Reply.RoundtripTime);
- bag.Add(new Host(ip, "mac", ""));
- }
- lock (lockObj)
- {
- upCount++;
- }
- }
- else if (e.Reply == null)
- {
- Console.WriteLine("Pinging {0} failed. (Null Reply object?)", ip);
- }
- countdown.Signal();
- }
- }
Add Comment
Please, Sign In to add comment