Write your own ping tool aspcool reprint www.aspcool.com Time: 2001-4-11 10:00:25 Readings: 2235
Write your own ping tools: ping is a tool for detecting network connection speeds. The following article will be introduced in C # to use System.Net.Sockets to create a ping tool. -------------------------------------------------- ------------------------------ ping is a tool for detecting network connection speed, it will be given A socket connection is created between the remote host name and sends a packet of ICMP protocol format, and then the remote host responds, send back a packet, and we can determine the connection by calculating the time interval of sending to the received packet. speed. How to use Ping
Here is the code: ///ping.cs namespace saurabhping {using system; using system.net; using system.net.sockets; ///
new Socket (AddressFamily.AfINet, SocketType.SockRaw, ProtocolType.ProtICMP); // Get the server endpoint try {serverHE = DNS.GetHostByName (host);} catch (Exception) {Console.WriteLine ( "Host not found"); // fail return;} // Convert the server IP_EndPoint to an EndPoint IPEndPoint ipepServer = new IPEndPoint (serverHE.AddressList [0], 0); EndPoint epServer = (ipepServer); // Set the receiving endpoint to the client machine fromHE = DNS.GetHostByName (DNS.GetHostName ()); IPEndPoint ipEndPointFrom = new IPEndPoint (fromHE.AddressList [0], 0); EndPoint EndPointFrom = (ipEndPointFrom); int PacketSize = 0; IcmpPacket packet = new IcmpPacket (); // Construct The packet to send packet.type = icmp_echo; // 8 packet.subcode = 0; packet.checksum = uint16.parse ("0"); packet.Identifier = uint16.parse ("45"); packet.sequencenumber = uint16 .PARSE ("0"); int pingdata = 32; // sizeof (icmppacket) - 8; packet.data = new byte [pingdata]; // ini Tilize the packet.data for (int i = 0; i } // now get this critter into a UInt16 array // Get the Half size of the Packet Double double_length = Convert.ToDouble (Index); Double dtemp = Math.Ceil (double_length / 2); int cksum_buffer_length = Convert.ToInt32 (dtemp ); // Create a Byte Array UInt16 [] cksum_buffer = new UInt16 [cksum_buffer_length]; // Code to initialize the Uint16 array int icmp_header_buffer_index = 0; for (int i = 0; i // loop for checking the time of the server responding while (recd!) {NBytes = socket.ReceiveFrom (ReceiveBuffer, 256, 0, ref EndPointFrom); if (nBytes == SOCKET_ERROR) {Console.WriteLine ( "Host not Responding" ); Recd = true; break;} else if (nbytes> 0) {dwstop = system.environment.tickcount - dwstart; // stop timing console.writeline ("reply from" epserver.tostring () "in" DWSTOP "MS: BYtes Received" nbytes); recd = true; break;} timeout = system.environment; if (timeout> 1000) {console.writeline ("time out"); recd = true;} } // close the socket socket.close ();} ///