C#中實現Ping

來源:互聯網
上載者:User

在C#中實現Ping,代碼如下:

using System;<br />using System.Net;<br />using System.Net.Sockets;<br />///ping.cs<br />namespace SystemMonitor {<br />///<br />/// 主要的類:ping<br />///<br />class Ping {<br />//聲明幾個常量<br />const int SOCKET_ERROR = -1;<br />const int ICMP_ECHO = 8;<br />///<br />/// 這裡取得Hostname參數<br />///<br />public static void PingUrl(string[] argv) {<br />if(argv.Length==0) {<br />//If user did not enter any Parameter inform him<br />Console.WriteLine("Usage:Ping /r") ;<br />Console.WriteLine(" The name of the Host who you want to ping");<br />Console.WriteLine("/r Ping the host continuously") ;<br />}<br />else if(argv.Length==1) {<br />//Just the hostname provided by the user<br />//call the method "PingHost" and pass the HostName as a parameter<br />PingHost(argv[0]) ;<br />}<br />else if(argv.Length==2) {<br />//the user provided the hostname and the switch<br />if(argv[1]=="/r") {<br />//loop the ping program<br />while(true) {<br />//call the method "PingHost" and pass the HostName as a parameter<br />PingHost(argv[0]) ;<br />}<br />}<br />else {<br />//if the user provided some other switch<br />PingHost(argv[0]) ;<br />}<br />}<br />else {<br />//Some error occurred<br />Console.WriteLine("Error in Arguments") ;<br />}<br />}<br />///<br />/// 主要的方法,用來取得IP,<br />/// 並計算回應時間<br />///<br />public static void PingHost(string host) {<br />//Declare the IPHostEntry<br />IPHostEntry serverHE, fromHE;<br />int nBytes = 0;<br />int dwStart = 0, dwStop = 0;<br />//Initilize a Socket of the Type ICMP<br />Socket socket =<br />new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.Icmp);<br />// Get the server endpoint<br />try {<br />serverHE = Dns.GetHostByName(host);<br />}<br />catch(Exception) {<br />Console.WriteLine("Host not found"); // fail<br />return ;<br />}<br />// Convert the server IP_EndPoint to an EndPoint<br />IPEndPoint ipepServer = new IPEndPoint(serverHE.AddressList[0], 0);<br />EndPoint epServer = (ipepServer);<br />// Set the receiving endpoint to the client machine<br />fromHE = Dns.GetHostByName(Dns.GetHostName());<br />IPEndPoint ipEndPointFrom = new IPEndPoint(fromHE.AddressList[0], 0);<br />EndPoint EndPointFrom = (ipEndPointFrom);<br />int PacketSize = 0;<br />IcmpPacket packet = new IcmpPacket();<br />// Construct the packet to send<br />packet.Type = ICMP_ECHO; //8<br />packet.SubCode = 0;<br />packet.CheckSum = UInt16.Parse("0");<br />packet.Identifier = UInt16.Parse("45");<br />packet.SequenceNumber = UInt16.Parse("0");<br />int PingData = 32; // sizeof(IcmpPacket) - 8;<br />packet.Data = new Byte[PingData];<br />//Initilize the Packet.Data<br />for (int i = 0; i &lt; PingData; i++) {<br />packet.Data[i] = (byte)'#';<br />}<br />//Variable to hold the total Packet size<br />PacketSize = PingData + 8;<br />Byte [] icmp_pkt_buffer = new Byte[ PacketSize ];<br />Int32 Index = 0;<br />//Call a Method Serialize which counts<br />//The total number of Bytes in the Packet<br />Index = Serialize(<br />packet,<br />icmp_pkt_buffer,<br />PacketSize,<br />PingData );<br />//Error in Packet Size<br />if( Index == -1 ) {<br />Console.WriteLine("Error in Making Packet");<br />return ;<br />}<br />// now get this critter into a UInt16 array<br />//Get the Half size of the Packet<br />Double double_length = Convert.ToDouble(Index);<br />Double dtemp = Math.Ceiling( double_length / 2);<br />int cksum_buffer_length = Convert.ToInt32(dtemp);<br />//Create a Byte Array<br />UInt16 [] cksum_buffer = new UInt16[cksum_buffer_length];<br />//Code to initialize the Uint16 array<br />int icmp_header_buffer_index = 0;<br />for( int i = 0; i &lt; cksum_buffer_length; i++ ) {<br />cksum_buffer[i] =<br />BitConverter.ToUInt16(icmp_pkt_buffer,icmp_header_buffer_index);<br />icmp_header_buffer_index += 2;<br />}<br />//Call a method which will return a checksum<br />UInt16 u_cksum = checksum(cksum_buffer, cksum_buffer_length);<br />//Save the checksum to the Packet<br />packet.CheckSum = u_cksum;<br />// Now that we have the checksum, serialize the packet again<br />Byte [] sendbuf = new Byte[ PacketSize ];<br />//again check the packet size<br />Index = Serialize(<br />packet,<br />sendbuf,<br />PacketSize,<br />PingData );<br />//if there is a error report it<br />if( Index == -1 ) {<br />Console.WriteLine("Error in Making Packet");<br />return ;<br />}<br />dwStart = System.Environment.TickCount; // Start timing<br />//send the Pack over the socket<br />if ((nBytes = socket.SendTo(sendbuf, PacketSize, 0, epServer)) == SOCKET_ERROR) {<br />Console.WriteLine("Socket Error cannot Send Packet");<br />}<br />// Initialize the buffers. The receive buffer is the size of the<br />// ICMP header plus the IP header (20 bytes)<br />Byte [] ReceiveBuffer = new Byte[256];<br />nBytes = 0;<br />//Receive the bytes<br />bool recd =false ;<br />int timeout=0 ;<br />//loop for checking the time of the server responding<br />while(!recd) {<br />nBytes = socket.ReceiveFrom(ReceiveBuffer, 256, 0, ref EndPointFrom);<br />if (nBytes == SOCKET_ERROR) {<br />Console.WriteLine("Host not Responding") ;<br />recd=true ;<br />break;<br />}<br />else if(nBytes&gt;0) {<br />dwStop = System.Environment.TickCount - dwStart; // stop timing<br />Console.WriteLine("Reply from "+epServer.ToString()+" in "<br />+dwStop+"MS :Bytes Received"+nBytes);<br />recd=true;<br />break;<br />}<br />timeout=System.Environment.TickCount - dwStart;<br />if(timeout&gt;1000) {<br />Console.WriteLine("Time Out") ;<br />recd=true;<br />}<br />}<br />//close the socket<br />socket.Close();<br />}<br />///<br />/// This method get the Packet and calculates the total size<br />/// of the Pack by converting it to byte array<br />///<br />public static Int32 Serialize(IcmpPacket packet, Byte[] Buffer,<br />Int32 PacketSize, Int32 PingData ) {<br />Int32 cbReturn = 0;<br />// serialize the struct into the array<br />int Index=0;<br />Byte [] b_type = new Byte[1];<br />b_type[0] = (packet.Type);<br />Byte [] b_code = new Byte[1];<br />b_code[0] = (packet.SubCode);<br />Byte [] b_cksum = BitConverter.GetBytes(packet.CheckSum);<br />Byte [] b_id = BitConverter.GetBytes(packet.Identifier);<br />Byte [] b_seq = BitConverter.GetBytes(packet.SequenceNumber);<br />// Console.WriteLine("Serialize type ");<br />Array.Copy( b_type, 0, Buffer, Index, b_type.Length );<br />Index += b_type.Length;<br />// Console.WriteLine("Serialize code ");<br />Array.Copy( b_code, 0, Buffer, Index, b_code.Length );<br />Index += b_code.Length;<br />// Console.WriteLine("Serialize cksum ");<br />Array.Copy( b_cksum, 0, Buffer, Index, b_cksum.Length );<br />Index += b_cksum.Length;<br />// Console.WriteLine("Serialize id ");<br />Array.Copy( b_id, 0, Buffer, Index, b_id.Length );<br />Index += b_id.Length;<br />Array.Copy( b_seq, 0, Buffer, Index, b_seq.Length );<br />Index += b_seq.Length;<br />// copy the data<br />Array.Copy( packet.Data, 0, Buffer, Index, PingData );<br />Index += PingData;<br />if( Index != PacketSize/* sizeof(IcmpPacket) */) {<br />cbReturn = -1;<br />return cbReturn;<br />}<br />cbReturn = Index;<br />return cbReturn;<br />}<br />///<br />/// This Method has the algorithm to make a checksum<br />///<br />public static UInt16 checksum( UInt16[] buffer, int size ) {<br />Int32 cksum = 0;<br />int counter;<br />counter = 0;<br />while ( size &gt; 0 ) {<br />UInt16 val = buffer[counter];<br />cksum += Convert.ToInt32( buffer[counter] );<br />counter += 1;<br />size -= 1;<br />}<br />cksum = (cksum &gt;&gt; 16) + (cksum &amp; 0xffff);<br />cksum += (cksum &gt;&gt; 16);<br />return (UInt16)(~cksum);<br />}<br />} // class ping<br />///<br />/// Class that holds the Pack information<br />///<br />public class IcmpPacket {<br />public Byte Type; // type of message<br />public Byte SubCode; // type of sub code<br />public UInt16 CheckSum; // ones complement checksum of struct<br />public UInt16 Identifier; // identifier<br />public UInt16 SequenceNumber; // sequence number<br />public Byte [] Data;<br />} // class IcmpPacket<br />}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.