• 本文介绍C# ping命令的实现方法,首先利用原始Socket套接字,实现ICMP协议,然后执行ping命令。最后,还可以使用C# 2.0中新增的Ping类来实现。
  • 以下介绍C# ping命令的两种实现方法。

    C# ping命令实现:利用原始Socket套接字,实现ICMP协议。

    1. using System;
    2. using System.Collections.Generic;
    3. using System.Text;
    4. using System.Net;
    5. using System.Net.Sockets;
    6. namespace PingC
    7. {
    8. class ping
    9. {
    10. const int SOCKET_ERROR = -1;
    11. const int ICMP_ECHO = 8;
    12. static void Main(string[] args)
    13. {
    14. ping p = new ping();
    15. Console.WriteLine("请输入要 Ping 的IP或者主机名字:");
    16. string MyUrl = Console.ReadLine();
    17. Console.WriteLine("正在 Ping " + MyUrl + " ……");
    18. Console.Write(p.PingHost(MyUrl));
    19. }
    20. public string PingHost(string host)
    21. {
    22. // 声明 IPHostEntry
    23. IPHostEntry ServerHE, fromHE;
    24. int nBytes = 0;
    25. int dwStart = 0, dwStop = 0;
    26. //初始化ICMP的Socket
    27. Socket socket =
    28. new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.Icmp);
    29. socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, 1000);
    30. // 得到Server EndPoint
    31. try
    32. {
    33. ServerHE = Dns.GetHostByName(host);
    34. }
    35. catch (Exception)
    36. {
    37. return "没有发现主机";
    38. }
    39. // 把 Server IP_EndPoint转换成EndPoint
    40. IPEndPoint ipepServer = new IPEndPoint(ServerHE.AddressList[0], 0);
    41. EndPoint epServer = (ipepServer);
    42. // 设定客户机的接收Endpoint
    43. fromHE = Dns.GetHostByName(Dns.GetHostName());
    44. IPEndPoint ipEndPointFrom = new IPEndPoint(fromHE.AddressList[0], 0);
    45. EndPoint EndPointFrom = (ipEndPointFrom);
    46. int PacketSize = 0;
    47. IcmpPacket packet = new IcmpPacket();
    48. // 构建要发送的包
    49. packet.Type = ICMP_ECHO; //8
    50. packet.SubCode = 0;
    51. packet.CheckSum =0;
    52. packet.Identifier = 45;
    53. packet.SequenceNumber = 0;
    54. int PingData = 24; // sizeof(IcmpPacket) - 8;
    55. packet.Data = new Byte[PingData];
    56. // 初始化Packet.Data
    57. for (int i = 0; i <  PingData; i++)
    58. {
    59. packet.Data[i] = (byte)'#';
    60. }
    61. //Variable to hold the total Packet size
    62. PacketSize = 32;
    63. Byte[] icmp_pkt_buffer = new Byte[PacketSize];
    64. Int32 Index = 0;
    65. //again check the packet size
    66. Index = Serialize(
    67. packet,
    68. icmp_pkt_buffer,
    69. PacketSize,
    70. PingData);
    71. //if there is a error report it
    72. if (Index == -1)
    73. {
    74. return "Error Creating Packet";
    75. }
    76. // convert into a UInt16 array
    77. //Get the Half size of the Packet
    78. Double double_length = Convert.ToDouble(Index);
    79. Double dtemp = Math.Ceiling(double_length / 2);
    80. int cksum_buffer_length = Index/2;
    81. //Create a Byte Array
    82. UInt16[] cksum_buffer = new UInt16[cksum_buffer_length];
    83. //Code to initialize the Uint16 array
    84. int icmp_header_buffer_index = 0;
    85. for (int i = 0; i <  cksum_buffer_length; i++)
    86. {
    87. cksum_buffer[i] =
    88. BitConverter.ToUInt16(icmp_pkt_buffer, icmp_header_buffer_index);
    89. icmp_header_buffer_index += 2;
    90. }
    91. //Call a method which will return a checksum
    92. UInt16 u_cksum = checksum(cksum_buffer, cksum_buffer_length);
    93. //Save the checksum to the Packet
    94. packet.CheckSum = u_cksum;
    95. // Now that we have the checksum, serialize the packet again
    96. Byte[] sendbuf = new Byte[PacketSize];
    97. //again check the packet size
    98. Index = Serialize(
    99. packet,
    100. sendbuf,
    101. PacketSize,
    102. PingData);
    103. //if there is a error report it
    104. if (Index == -1)
    105. {
    106. return "Error Creating Packet";
    107. }
    108. dwStart = System.Environment.TickCount; // Start timing
    109. //send the Packet over the socket
    110. if ((nBytes = socket.SendTo(sendbuf, PacketSize, 0, epServer)) == SOCKET_ERROR)
    111. {
    112. return "Socket Error: cannot send Packet";
    113. }
    114. // Initialize the buffers. The receive buffer is the size of the
    115. // ICMP header plus the IP header (20 bytes)
    116. Byte[] ReceiveBuffer = new Byte[256];
    117. nBytes = 0;
    118. //Receive the bytes
    119. bool recd = false;
    120. int timeout = 0;
    121. //loop for checking the time of the server responding
    122. while (!recd)
    123. {
    124. nBytes = socket.ReceiveFrom(ReceiveBuffer, 256, 0, ref EndPointFrom);
    125. if (nBytes == SOCKET_ERROR)
    126. {
    127. return "主机没有响应";
    128. }
    129. else if (nBytes > 0)
    130. {
    131. dwStop = System.Environment.TickCount - dwStart; // stop timing
    132. return "Reply from " + epServer.ToString() + " in "
    133. + dwStop + "ms.  Received: " + nBytes + " Bytes.";
    134. }
    135. timeout = System.Environment.TickCount - dwStart;
    136. if (timeout > 1000)
    137. {
    138. return "超时";
    139. }
    140. }
    141. //close the socket
    142. socket.Close();
    143. return "";
    144. }
    145. /// < summary>
    146. ///  This method get the Packet and calculates the total size
    147. ///  of the Pack by converting it to byte array
    148. /// < /summary>
    149. public static Int32 Serialize(IcmpPacket packet, Byte[] Buffer,
    150. Int32 PacketSize, Int32 PingData)
    151. {
    152. Int32 cbReturn = 0;
    153. // serialize the struct into the array
    154. int Index = 0;
    155. Byte[] b_type = new Byte[1];
    156. b_type[0] = (packet.Type);
    157. Byte[] b_code = new Byte[1];
    158. b_code[0] = (packet.SubCode);
    159. Byte[] b_cksum = BitConverter.GetBytes(packet.CheckSum);
    160. Byte[] b_id = BitConverter.GetBytes(packet.Identifier);
    161. Byte[] b_seq = BitConverter.GetBytes(packet.SequenceNumber);
    162. Array.Copy(b_type, 0, Buffer, Index, b_type.Length);
    163. Index += b_type.Length;
    164. Array.Copy(b_code, 0, Buffer, Index, b_code.Length);
    165. Index += b_code.Length;
    166. Array.Copy(b_cksum, 0, Buffer, Index, b_cksum.Length);
    167. Index += b_cksum.Length;
    168. Array.Copy(b_id, 0, Buffer, Index, b_id.Length);
    169. Index += b_id.Length;
    170. Array.Copy(b_seq, 0, Buffer, Index, b_seq.Length);
    171. Index += b_seq.Length;
    172. // copy the data
    173. Array.Copy(packet.Data, 0, Buffer, Index, PingData);
    174. Index += PingData;
    175. if (Index != PacketSize/* sizeof(IcmpPacket)  */)
    176. {
    177. cbReturn = -1;
    178. return cbReturn;
    179. }
    180. cbReturn = Index;
    181. return cbReturn;
    182. }
    183. /// < summary>
    184. ///  This Method has the algorithm to make a checksum
    185. /// < /summary>
    186. public static UInt16 checksum(UInt16[] buffer, int size)
    187. {
    188. Int32 cksum = 0;
    189. int counter;
    190. counter = 0;
    191. while (size > 0)
    192. {
    193. UInt16 val = buffer[counter];
    194. cksum += buffer[counter];
    195. counter += 1;
    196. size -= 1;
    197. }
    198. cksum = (cksum >> 16) + (cksum & 0xffff);
    199. cksum += (cksum >> 16);
    200. return (UInt16)(~cksum);
    201. }
    202. }
    203. /// 类结束
    204. /// < summary>
    205. ///  Class that holds the Pack information
    206. /// < /summary>
    207. public class IcmpPacket
    208. {
    209. public Byte Type;    // type of message
    210. public Byte SubCode;    // type of sub code
    211. public UInt16 CheckSum;   // ones complement checksum of struct
    212. public UInt16 Identifier;      // identifier
    213. public UInt16 SequenceNumber;     // sequence number
    214. public Byte[] Data;
    215. } // class IcmpPacket
    216. }

    C# ping命令执行:执行ping命令

    首先,我们用使用Process类,来创建独立的进程,导入System.Diagnostics,

    using System.Diagnostics;

    实例一个Process类,启动一个独立进程

    Process p = new Process();

    Process类有一个StartInfo属性,这个是ProcessStartInfo类,包括了一些属性和方法,

    下面我们用到了他的几个属性:

    设定程序名

    p.StartInfo.FileName = "cmd.exe";

    关闭Shell的使用

    p.StartInfo.UseShellExecute = false;

    重定向标准输入

    p.StartInfo.RedirectStandardInput = true;

    重定向标准输出

    p.StartInfo.RedirectStandardOutput = true;

    重定向错误输出

    p.StartInfo.RedirectStandardError = true;

    设置不显示窗口

    p.StartInfo.CreateNoWindow = true;

    上面几个属性的设置是比较关键的一步。

    既然都设置好了那就启动进程吧,

    p.Start();

    输入要执行的命令,这里就是ping了,

    p.StandardInput.WriteLine("ping -n 1 www.iwebtrados.com.cn");

    p.StandardInput.WriteLine("exit");

    从输出流获取命令执行结果,

    string strRst = p.StandardOutput.ReadToEnd();

    C# ping命令实现:利用c#2.0新增的Ping类

    这里我写的是一个窗体程序。首先添加textbox,listbox,button控件,其中textbox录入域名或IP,listbox显示结果.

    在button1_click事件键入

    1. private void button1_Click(object sender, EventArgs e)
    2. {
    3. Ping p1 = new Ping(); //只是演示,没有做错误处理
    4. PingReply reply = p1.Send(this.textBox1.Text);//阻塞方式
    5. displayReply(reply); //显示结果
    6. }
    7. private void displayReply(PingReply reply) //显示结果
    8. {
    9. StringBuilder sbuilder ;
    10. if (reply.Status == IPStatus.Success)
    11. {
    12. sbuilder = new StringBuilder();
    13. sbuilder.Append(string.Format("Address: {0} ", reply.Address.ToString ()));
    14. sbuilder.Append(string.Format("RoundTrip time: {0} ", reply.RoundtripTime));
    15. sbuilder.Append(string.Format("Time to live: {0} ", reply.Options.Ttl));
    16. sbuilder.Append(string.Format("Don't fragment: {0} ", reply.Options.DontFragment));
    17. sbuilder.Append(string.Format("Buffer size: {0} ", reply.Buffer.Length));
    18. listBox1.Items.Add(sbuilder.ToString());
    19. }
    20. }

    也可以做异步的处理,修改button1_click,并添加PingCompletedCallBack方法

    1. private void button1_Click(object sender, EventArgs e)
    2. {
    3. Ping p1 = new Ping();
    4. p1.PingCompleted += new PingCompletedEventHandler(this.PingCompletedCallBack);//设置PingCompleted事件处理程序
    5. p1.SendAsync(this.textBox1.Text, null);
    6. }
    7. private void PingCompletedCallBack(object sender, PingCompletedEventArgs e)
    8. {
    9. if (e.Cancelled)
    10. {
    11. listBox1.Items.Add("Ping Canncel");
    12. return;
    13. }
    14. if (e.Error != null)
    15. {
    16. listBox1.Items.Add(e.Error.Message);
    17. return;
    18. }
    19. StringBuilder sbuilder;
    20. PingReply reply = e.Reply;
    21. if (reply.Status == IPStatus.Success)
    22. {
    23. sbuilder = new StringBuilder();
    24. sbuilder.Append(string.Format("Address: {0} ", reply.Address.ToString()));
    25. sbuilder.Append(string.Format("RoundTrip time: {0} ", reply.RoundtripTime));
    26. sbuilder.Append(string.Format("Time to live: {0} ", reply.Options.Ttl));
    27. sbuilder.Append(string.Format("Don't fragment: {0} ", reply.Options.DontFragment));
    28. sbuilder.Append(string.Format("Buffer size: {0} ", reply.Buffer.Length));
    29. listBox1.Items.Add(sbuilder.ToString());
    30. }
    31. }

    怎么样,相比1、2方式,3是不是简单的多呀。

    本文来自网络小筑的博客:《c#下实现ping操作》。

C# ping命令的实现方法:Ping类的使用相关推荐

  1. 计算机网络中ping命令的使用方法,ping命令的基础使用技巧

    在电脑基础操作中,很多人在操作电脑中可以接触到这个ping命令.但是都是没有深入的去了解这个ping命令.对于ping命令在电脑中可以通过ping来判断及解决网络故障.我们每天都接触电脑使用互联网的人 ...

  2. 响应因特网端口ping命令_如何使用Ping命令识别基本的Internet问题

    响应因特网端口ping命令 Next time you call your help desk, do you want to wow them with your networking knowle ...

  3. ping命令简单介绍+用ping简单测网速

    ping命令简单介绍+用ping简单测网速 ping可以用来检查网络是否通畅或者网络连接速度,而作为网络管理员ping命令是第一个必须掌握的DOS命令.我们可以用ping来给网络上指定IP的计算机发送 ...

  4. 【无标题】使用Ping命令制作的批量Ping工具,可对指定Ip进行ping测试,并将结果记录到txt文件

    //使用Ping命令制作的批量Ping工具,可对指定Ip进行ping测试,并将结果记录到txt文件 直接闪退出去了,不知道问题出在哪里. //代码: @if "%~1"==&quo ...

  5. php ping 命令注入,CTF关于ping命令注入问题

    题目样式 对于看到ping或者ping命令却没有弄waf时就要想到命令注入. 具体注入方法 看到ping命令就可以利用截断来执行新的命令. 首先测试所有的截断符号: '$' ';' '|' '-' ' ...

  6. 全面掌握ping命令(四)ping命令常用参数

    参数可以对命令的功能进行扩展,ping命令的参数比较多,常用的主要有以下几个: (1)ping IP地址 –t 连续不停对IP地址发送ICMP数据包,直到被用户以Ctrl+C中断. 如:ping 19 ...

  7. 全面掌握ping命令(三) ping命令防火墙设置

    Ping命令利用ICMP协议工作,ICMP是一个比较复杂的协议,功能强大,也经常被黑客利用来攻击网络上的路由器和主机,所以目前的很多网络设备或防火墙都提供了禁用ICMP协议的功能.如Windows系统 ...

  8. ping网站服务器,ping命令的作用,ping真能检测出服务器的快慢吗??

    卖服务器的时候总有客户问给个ip来ping下看看快不快~~,ping真的能测试出快不快吗? Ping是Windows系列自带的一个可执行命令.对于站长来说,利用它可以检查服务器网络是否能够连通,可以帮 ...

  9. python调用ping命令_python调用系统命令ping

    #! /usr/bin/env python #coding=utf-8 ############# import subprocess import time import os ks=int(ti ...

最新文章

  1. safari浏览器横屏怎么设置_Safari浏览器的几个小技巧你掌握了吗?
  2. 用html编写ASCII表,[html_css]ASCII编码表
  3. CVE-2016-1779技术分析及其背后的故事
  4. Jmeter简介以及简单模拟性能测试
  5. PMCAFF产品经理第一课 | 「在行」价值1.5万元的强大课程体系,365天能力突围
  6. Fegion-4解决Fegion第一次请求timeout的问题
  7. SystemC 代码添加和测试方法
  8. 深入java虚拟机需要读吗_《深入理解Java虚拟机》读后总结(一)JVM内存模型
  9. 思维方式是看待事物的角度、方式和方法,它对人的言行起到决定性作用
  10. 【转载】素数快速打表(据说是线性复杂度)
  11. ubuntu skill
  12. DDD领域驱动设计:四层架构应用
  13. 力学流体simple
  14. 计算机win7开超级性能模式,win7系统设置最高性能的操作方法
  15. 集合框架--集合框架体系概述
  16. 芯片设计:verilog断言(SVA)语法
  17. 大OA核心——工作流系统(引擎)
  18. 服务器omv系统,在Debian上安装OpenMediaVault开源NAS系统
  19. 从one hot vector到Attention, Bert——NLP基本思想串连回顾
  20. 微机原理与接口技术 重点详解与章节总结——8086微处理器系统结构

热门文章

  1. Android使用RecyclerView显示最新电影
  2. 前端百题斩【019】——数组中方法原理早知道
  3. Wireshark 基础使用-过滤并查看抓包数据
  4. Ae:常用内置抠像效果
  5. UVM进程的同步之uvm_event
  6. 2022打造新私域增长涡轮
  7. 使用 disk-image-block制作centos7的镜像
  8. 中以海德携手百度健康 探讨AI助力乙肝防治
  9. HILLSTONE sg6000 g5150 怎么恢复出厂设置
  10. manifold2-G刷机(镜像备份与恢复出厂设置)