c# 下实现ping 命令操作

1>通过.net提供的类实现

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5
 6 using System.Diagnostics;
 7 using System.Net.NetworkInformation;
 8
 9 namespace ConsoleApplication1
10 {
11     class Program
12     {
13         static void Main(string[] args)
14         {
15             Ping ping = new Ping();
16             Console.WriteLine(ping.Send("192.168.0.33").Status);
17             Console.Read();
18         }
19     }
20
21 }

2>同过调用cmd 的ping实现

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5
 6 using System.Diagnostics;
 7 using System.Net.NetworkInformation;
 8
 9 namespace ConsoleApplication1
10 {
11     class Program
12     {
13         static void Main(string[] args)
14         {
15             Console.WriteLine(PingByProcess("192.168.0.33"));
16             Console.Read();
17         }
18
19          static string PingByProcess(string ip)
20         {
21             using (Process p = new Process())
22             {
23                 p.StartInfo.FileName = "cmd.exe";
24                 p.StartInfo.UseShellExecute = false;
25                 p.StartInfo.RedirectStandardInput = true;
26                 p.StartInfo.RedirectStandardOutput = true;
27                 p.StartInfo.RedirectStandardError = true;
28                 p.StartInfo.CreateNoWindow = true;
29
30                 p.Start();
31                 p.StandardInput.WriteLine(string.Format("ping -n 1 {0}", ip));
32                 return p.StandardOutput.ReadToEnd();
33             }
34         }
35     }
36
37 }

3>利用原始Socket套接字,实现ICMP协议。

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

using System.Diagnostics;
using System.Net.NetworkInformation;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            PingHelp p = new PingHelp();
            Console.WriteLine(p.PingHost("192.168.0.120"));
            Console.Read();
        }
    }

}
时间: 2024-10-11 01:30:08

c# 下实现ping 命令操作的相关文章

ubuntu 下安装ping 命令工具

使用docker仓库下载的ubuntu 14.04 镜像.里面精简的连 ping 命令都没有.google 百度都搜索不到ping 命令在哪个包里. 努力找了半天,在一篇文件的字里行间发现了 ping 的来历- [email protected]:/# apt-get install inetutils-ping 还有ifconfig   可以用 apt-get install net-tools 来安装-

linux下安装 ping 命令

使用docker仓库下载的ubuntu 14.04 镜像.里面精简的连 ping 命令都没有.google 百度都搜索不到ping 命令在哪个包里. 努力找了半天,在一篇文章的字里行间发现了 ping 的来历- [email protected]:/# apt-get install inetutils-ping 还有ifconfig   可以用 apt-get install net-tools 来安装- --------------------------------------------

002-Linux下防火墙相关命令操作

linux的各个版本或同一个版本间不同版本号关于防火墙命令也会有不一样的.针对这些命令整理如下,方便自己或有需要的朋友查阅. centOS 6.5关闭防火墙步骤 关闭命令:         service iptables stop 永久关闭防火墙:chkconfig iptables off 两个命令同时运行,运行完成后查看防火墙关闭状态 service iptables status centos7.0默认防火墙为firewalld(为了测试,关闭默认防火墙,使用iptables防火墙) s

Linux和Windows下ping命令详解

转:http://linux.chinaitlab.com/command/829332.html 一.Linux下的ping参数 用途 发送一个回送信号请求给网络主机. 语法 ping [ -d] [ -D ] [ -n ] [ -q ] [ -r] [ -v] [ \ -R ] [ -a addr_family ] [ -c Count ] [ -w timeout ] [ -f | -i \ Wait ] [ -l Preload ] [ -p Pattern ] [ -s PacketS

Linux下如何使用ping命令

转自:http://q16964777.blog.163.com/blog/static/250555066201561744149503/ Linux下的ping命令用于查看网络上的主机是否在工作.执行ping指令会使用ICMP传输协议,发出要求回应的信息,若远端主机的网络功能没有问题,就会回应该信息,因而得知该主机运作正常.ping命令的一般格式为:ping [-dfnqrRv][-c<发送次数>][-i<间隔秒数>][-I<网络界面>][-l<前置载 入&g

docker下centos安装ping命令

https://blog.csdn.net/king_gun/article/details/78423115 [问题] 从docker hub上拉取到则镜像centos:6.7在执行ping命令是报错: [[email protected] /]# ping bash: ping: command not found 百度上搜索,查到linux下安装ping命令的方法为: apt-get install inetutils-ping 但是docker镜像中不存在apt-get指令,使用yum

Linux下禁止ping最简单的方法

LINUX下禁止ping命令的使用 以root进入Linux系统,然后编辑文件icmp_echo_ignore_allvi /proc/sys/net/ipv4/icmp_echo_ignore_all将其值改为1后为禁止PING将其值改为0后为解除禁止PING 直接修改会提示错误: WARNING: The file has been changed since reading it!!!Do you really want to write to it (y/n)?y"icmp_echo_i

Ping命令详解

引言:我们每天都在使用Ping命令,但是我们可能不太清楚Ping的工作原理,对运行结果中的很多细节也不是很清楚.查找了一下资料,现在和大家分享一下Ping的运行原理和相关细节. A.Ping命令的工作原理Ping命令主要用于测试本地主机与远程主机之间的连通性.Ping命令会向远程主机发送ICMP回应请求数据报(echo request),远程主机收到后回应应答数据报(echo reply).本地主机会计算从发送回应请求数据报到回应应答数据报返回之间的时间,从而确定本地主机与远程主机之间是否正常连

ping命令

1.工作原理: Ping命令会向远程主机发送ICMP回应请求数据报(echo request),远程主机收到后回应应答数据报(echo reply).本地主机会计算从发送回应请求数据报到回应应答数据报返回之间的时间,从而确定本地主机与远程主机之间是否正常连接,以及网络状况如何. 2.ping结果的意义: 对于Ping命令的运行结果,我们主要关注的是数据报返回时间,丢包率,从这两个因素上也就可以大致判断出网络是否稳定.当然这里的网络包括本地网络以及数据报所经过的路由结点的网络.比如数据报返回时间波