Ping
Add Comment<div align="center"> <table border="0" width="70%" class="outline"> <tr> <td width="50%" class="outline"><b>Download File</b></td> <td width="50%" class="outline"><b>SDK</b></td> </tr> <tr> <td width="50%" class="outline"><a href="../../file/ping.zip" class="wbox">ping.zip</a> (8kb)</td> <td width="50%" class="outline">Beta1</td> </tr> </table> </div> <p> <span class=wboxheado>Introduction</span><br> Ping is a very useful utility used to determine the speed of a Network Connection its also used in many other networking utilities. It sends a Data Packet using <b> ICMP</b> Protocol to the given Host. The Host then in reply sends back a Data Packet. The time taken to Send and Receive a Data Packet is calculated in Milliseconds. This helps us to know the speed of the connection. <br> In this example I use the Socket class from the "System.Net.Socket" namespace.<br> <br> I was on the look out for the code in C# for a long time finally I got it in the MSDN Magazine.<br> It was written by Lance Olson in his example Share Baby. I have changed his example to suit my needs.</p> <p><span class=wboxheado>Requirements</span><br> 1) This example uses .NET SDK beta1 (Note: This example might not run on the future versions of the SDK)</p> <p><span class=wboxheado>Usage</span><br> Ping <hostname> /r<br> where :<br> <hostname> - is the Host Address of the Server to Ping <br> /r - Optional Switch to ping continuously to the Host Name</p> <p><span class=wboxheado>Code</span></p> <p>1) <i><b>Ping.cs</b> :- The Ping Utility</i></p> <table border="0" width="100%" class="code" cellspacing="0" cellpadding="0"> <tr> <td width="100%"> <pre>namespace SaurabhPing { using System; using System.Net; using System.Net.Sockets; <span class=cmt>/// <summary> /// The Main Ping Class /// </summary></span> class Ping { <span class=cmt>//Declare some Constant Variables</span> const int SOCKET_ERROR = -1; const int ICMP_ECHO = 8; <span class=cmt>/// <summary> /// The Starting Point of the Class /// It Takes the Hostname parameter /// </summary></span> public static void Main(string[] argv) { if(argv.Length==0) { <span class=cmt>//If user did not enter any Parameter inform him</span> Console.WriteLine("Usage:Ping <hostname> /r") ; Console.WriteLine("<hostname> The name of the Host who you want to ping"); Console.WriteLine("/r Ping the host continuously") ; } else if(argv.Length==1) { <span class=cmt>//Just the hostname provided by the user //call the method "PingHost" and pass the //HostName as a parameter</span> PingHost(argv[0]) ; } else if(argv.Length==2) { <span class=cmt>//the user provided the hostname and the switch</span> if(argv[1]=="/r") { //loop the ping program while(true) { <span class=cmt>//call the method "PingHost" and pass the //HostName as a parameter</span> PingHost(argv[0]) ; } } else { <span class=cmt>//if the user provided some other switch</span> PingHost(argv[0]) ; } } else { <span class=cmt>//Some error occurred</span> Console.WriteLine("Error in Arguments") ; } } <span class=cmt> /// <summary> /// This method takes the "hostname" of the server /// and then it ping's it and shows the response time /// </summary></span> public static void PingHost(string host) { <span class=cmt>//Declare the IPHostEntry </span> IPHostEntry serverHE, fromHE; int nBytes = 0; int dwStart = 0, dwStop = 0; <span class=cmt>//Initialize a Socket of the Type ICMP</span> Socket socket = new Socket(AddressFamily.AfINet,SocketType.SockRaw,ProtocolType.ProtICMP); <span class=cmt>// Get the server endpoint</span> try { serverHE = DNS.GetHostByName(host); } catch(Exception) { Console.WriteLine("Host not found");<span class=cmt> // fail</span> return ; } <span class=cmt>// Convert the server IP_EndPoint to an EndPoint</span> IPEndPoint ipepServer = new IPEndPoint(serverHE.AddressList[0],0); EndPoint epServer = (ipepServer); <span class=cmt>// Set the receiving endpoint to the client machine</span> fromHE = DNS.GetHostByName(DNS.GetHostName()); IPEndPoint ipEndPointFrom = new IPEndPoint(fromHE.AddressList[0],0); EndPoint EndPointFrom = (ipEndPointFrom); int PacketSize = 0; IcmpPacket packet = new IcmpPacket(); <span class=cmt>// Construct the packet to send</span> packet.Type = ICMP_ECHO;<span class=cmt> //8</span> packet.SubCode = 0; packet.CheckSum = UInt16.Parse("0"); packet.Identifier = UInt16.Parse("45"); packet.SequenceNumber = UInt16.Parse("0"); int PingData = 32; <span class=cmt>// sizeof(IcmpPacket) - 8; </span> packet.Data = new Byte[PingData]; <span class=cmt>//Initialize the Packet.Data</span> for (int i = 0; i < PingData; i++) { packet.Data[i] = (byte)'#'; } <span class=cmt>//Variable to hold the total Packet size</span> PacketSize = PingData + 8; Byte [] icmp_pkt_buffer = new Byte[ PacketSize ]; Int32 Index = 0; <span class=cmt>//Call a Method Serialize which counts //The total number of Bytes in the Packet</span> Index = Serialize( packet, icmp_pkt_buffer, PacketSize, PingData ); <span class=cmt>//Error in Packet Size</span> if( Index == -1 ) { Console.WriteLine("Error in Making Packet"); return ; } <span class=cmt>// now get this critter into a UInt16 array //Get the Half size of the Packet</span> Double double_length = Convert.ToDouble(Index); Double dtemp = Math.Ceil( double_length / 2); int cksum_buffer_length = Convert.ToInt32(dtemp); <span class=cmt>//Create a Byte Array</span> UInt16 [] cksum_buffer = new UInt16[cksum_buffer_length]; <span class=cmt>//Code to initialize the Uint16 array </span> int icmp_header_buffer_index = 0; for( int i = 0; i < cksum_buffer_length; i++ ) { cksum_buffer[i] = BitConverter.ToUInt16(icmp_pkt_buffer,icmp_header_buffer_index); icmp_header_buffer_index += 2; } <span class=cmt>//Call a method which will return a checksum</span> UInt16 u_cksum = checksum(cksum_buffer, cksum_buffer_length); <span class=cmt>//Save the checksum to the Packet</span> packet.CheckSum = u_cksum; <span class=cmt>// Now that we have the checksum, serialize the packet again</span> Byte [] sendbuf = new Byte[ PacketSize ]; <span class=cmt>//again check the packet size</span> Index = Serialize( packet, sendbuf, PacketSize, PingData ); <span class=cmt>//if there is a error report it</span> if( Index == -1 ) { Console.WriteLine("Error in Making Packet"); return ; } dwStart = System.Environment.TickCount; <span class=cmt>// Start timing</span> <span class=cmt>//send the Pack over the socket</span> if ((nBytes = socket.SendTo(sendbuf, PacketSize, 0, epServer)) == SOCKET_ERROR) { Console.WriteLine("Socket Error cannot Send Packet"); } <span class=cmt>// Initialize the buffers. The receive buffer is the size of the // ICMP header plus the IP header (20 bytes)</span> Byte [] ReceiveBuffer = new Byte[256]; nBytes = 0; <span class=cmt>//Receive the bytes</span> bool recd =false ; int timeout=0 ; <span class=cmt>//loop for checking the time of the server responding </span> 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; <span class=cmt>// stop timing</span> Console.WriteLine("Reply from "+epServer.ToString()+" in " +dwStop+"MS :Bytes Received"+nBytes); recd=true; break; } timeout=System.Environment.TickCount - dwStart; if(timeout>1000) { Console.WriteLine("Time Out") ; recd=true; } } <span class=cmt>//close the socket</span> socket.Close(); } <span class=cmt>/// <summary> /// This method get the Packet and calculates the total size /// of the Pack by converting it to byte array /// </summary></span> public static Int32 Serialize(IcmpPacket packet, Byte[] Buffer, Int32 PacketSize, Int32 PingData ) { Int32 cbReturn = 0; <span class=cmt>// serialize the struct into the array</span> int Index=0; Byte [] b_type = new Byte[1]; b_type[0] = (packet.Type); Byte [] b_code = new Byte[1]; b_code[0] = (packet.SubCode); Byte [] b_cksum = BitConverter.GetBytes(packet.CheckSum); Byte [] b_id = BitConverter.GetBytes(packet.Identifier); Byte [] b_seq = BitConverter.GetBytes(packet.SequenceNumber); <span class=cmt>// Console.WriteLine("Serialize type ");</span> Array.Copy( b_type, 0, Buffer, Index, b_type.Length ); Index += b_type.Length; <span class=cmt>// Console.WriteLine("Serialize code ");</span> Array.Copy( b_code, 0, Buffer, Index, b_code.Length ); Index += b_code.Length; <span class=cmt>// Console.WriteLine("Serialize cksum ");</span> Array.Copy( b_cksum, 0, Buffer, Index, b_cksum.Length ); Index += b_cksum.Length; <span class=cmt>// Console.WriteLine("Serialize id ");</span> Array.Copy( b_id, 0, Buffer, Index, b_id.Length ); Index += b_id.Length; Array.Copy( b_seq, 0, Buffer, Index, b_seq.Length ); Index += b_seq.Length; <span class=cmt>// copy the data </span> Array.Copy( packet.Data, 0, Buffer, Index, PingData ); Index += PingData; if( Index != PacketSize/* sizeof(IcmpPacket) */) { cbReturn = -1; return cbReturn; } cbReturn = Index; return cbReturn; } <span class=cmt>/// <summary> /// This Method has the algorithm to make a checksum /// </summary></span> public static UInt16 checksum( UInt16[] buffer, int size ) { Int32 cksum = 0; int counter; counter = 0; while ( size > 0 ) { UInt16 val = buffer[counter]; cksum += Convert.ToInt32( buffer[counter] ); counter += 1; size -= 1; } cksum = (cksum >> 16) + (cksum & 0xffff); cksum += (cksum >> 16); return (UInt16)(~cksum); } } <span class=cmt>// class ping</span> <span class=cmt>/// <summary> /// Class that holds the Pack information /// </summary></span> public class IcmpPacket { public Byte Type; <span class=cmt>// type of message</span> public Byte SubCode; <span class=cmt>// type of sub code</span> public UInt16 CheckSum; <span class=cmt>// ones complement checksum of struct</span> public UInt16 Identifier; <span class=cmt>// identifier</span> public UInt16 SequenceNumber; <span class=cmt>// sequence number </span> public Byte [] Data; } <span class=cmt>// class IcmpPacket</span> }</pre> </td> </tr> </table>