Program.cs 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.Net.NetworkInformation;
  5. namespace PingList
  6. {
  7. class Program
  8. {
  9. static void Main(string[] args)
  10. {
  11. Console.ForegroundColor = ConsoleColor.Green;
  12. Console.WriteLine("本程序用来批量Ping IP地址列表并返回结果");
  13. Console.WriteLine("By 281Shenjian");
  14. if (!System.IO.File.Exists("IPs.txt"))
  15. {
  16. Console.ForegroundColor = ConsoleColor.Red;
  17. Console.WriteLine("\n没有找到文件IPs.txt,请新建一个文本文件,每个IP为一行,再运行本程序。");
  18. Console.WriteLine("\n按任意键退出!");
  19. Console.ReadKey();
  20. return;
  21. }
  22. Console.WriteLine("读取列表...");
  23. var list = System.IO.File.ReadAllLines("IPs.txt");
  24. StringBuilder sb = new StringBuilder();
  25. foreach (var item in list)
  26. {
  27. var r = ping(item, 1000);
  28. if (r == 1000)
  29. {
  30. Console.WriteLine(item + "......NOT Response");
  31. sb.AppendLine(item + "\tNOT Response");
  32. }
  33. else if (r == 99999)
  34. {
  35. Console.WriteLine(item + "......Err");
  36. sb.AppendLine(item + "\tErr");
  37. }
  38. else
  39. {
  40. Console.WriteLine(item + "......OK");
  41. sb.AppendLine(item + "\tOK");
  42. }
  43. }
  44. Console.WriteLine("All Done!");
  45. System.IO.File.WriteAllText("result.txt", sb.ToString());
  46. System.Diagnostics.Process.Start("result.txt");
  47. }
  48. static Ping pingSender = new Ping();
  49. static long ping(string ip,int timeout)
  50. {
  51. try
  52. {
  53. var pingReply = pingSender.Send(ip, timeout);
  54. if (pingReply.Status == IPStatus.Success)
  55. {
  56. return pingReply.RoundtripTime;
  57. }
  58. else
  59. {
  60. return timeout;
  61. }
  62. }
  63. catch (Exception err)
  64. {
  65. return 99999;
  66. }
  67. }
  68. }
  69. }