PING tool compiled by Asp.net

Source: Internet
Author: User
Tags socket error

PING is a tool used to detect the network connection speed. The following article describes how to use System. Net. Sockets in C # To create a PING tool.

--------------------------------------------------------------------------------

PING is a tool used to detect the network connection speed. It establishes a SOCKET connection between the local host and the remote host name and sends an ICMP packet to it, then the remote host responds and sends back a data packet. By calculating the time interval between the sent and received data packets, we can determine the connection speed.

Use ping

<Hostname> Host Name

[/R] The optional attribute determines whether to continuously ping the remote host.

The following code is used:

/// Ping. cs

Namespace SaurabhPing

{

Using System;

Using System. Net;

Using System. Net. Sockets;

/// <Summary>

/// Main class: ping

/// </Summary>

Class Ping

{

// Declare several Constants

Const int SOCKET_ERROR =-1;

Const int ICMP_ECHO = 8;

/// <Summary>

/// Obtain the Hostname Parameter

/// </Summary>

Public static void Main (string [] argv)

{

If (argv. Length = 0)

{

// If user did not enter any Parameter inform him

Console. WriteLine ("Usage: Ping

Console. WriteLine ("

Console. WriteLine ("/r Ping the host continuously ");

}

Else if (argv. Length = 1)

{

// Just the hostname provided by the user

// Call the method "PingHost" and pass the HostName as a parameter

PingHost (argv [0]);

}

Else if (argv. Length = 2)

{

// The user provided the hostname and the switch

If (argv [1] = "/r ")

{

// Loop the ping program

While (true)

{

// Call the method "PingHost" and pass the HostName as a parameter

PingHost (argv [0]);

}

}

Else

{

// If the user provided some other switch

PingHost (argv [0]);

}

}

Else

{

// Some error occurred

Console. WriteLine ("Error in Arguments ");

}

}

/// <Summary>

/// The main method used to obtain the IP address,

/// Calculate the response time

/// </Summary>

Public static void PingHost (string host)

{

// Declare the IPHostEntry

IPHostEntry serverHE, fromHE;

Int nBytes = 0;

Int dwStart = 0, dwStop = 0;

// Initilize a Socket of the Type ICMP

Socket socket =

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 processing ing 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];

// Initilize the Packet. Data

For (int I = 0; I <PingData; I ++)

{

Packet. Data [I] = (byte )#;

}

// Variable to hold the total Packet size

PacketSize = PingData + 8;

Byte [] icmp_pkt_buffer = new Byte [PacketSize];

Int32 Index = 0;

// Call a Method Serialize which counts

// The total number of Bytes in the Packet

Index = Serialize (

Packet,

Icmp_pkt_buffer,

PacketSize,

PingData );

// Error in Packet Size

If (Index =-1)

{

Console. WriteLine ("Error in Making Packet ");

Return;

}

// 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 <cksum_buffer_length; I ++ ){

Cksum_buffer [I] =

BitConverter. ToUInt16 (icmp_pkt_buffer, icmp_header_buffer_index );

Icmp_header_buffer_index + = 2;

}

// Call a method which will return a checksum

UInt16 u_cksum = checksum (cksum_buffer, cksum_buffer_length );

// Save the checksum to the Packet

Packet. CheckSum = u_cksum;

// Now that we have the checksum, serialize the packet again

Byte [] sendbuf = new Byte [PacketSize];

// Again check the packet size

Index = Serialize (

Packet,

Sendbuf,

PacketSize,

PingData );

// If there is a error report it

If (Index =-1)

{

Console. WriteLine ("Error in Making Packet ");

Return;

}

DwStart = System. Environment. TickCount; // Start timing

// Send the Pack over the socket

If (nBytes = socket. SendTo (sendbuf, PacketSize, 0, epServer) = SOCKET_ERROR)

{

Console. WriteLine ("Socket Error cannot Send Packet ");

}

// Initialize the buffers. The receive buffer is the size of

// ICMP header plus the IP header (20 bytes)

Byte [] ReceiveBuffer = new Byte [1, 256];

NBytes = 0;

// Receive the bytes

Bool recd = false;

Int timeout = 0;

// 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. TickCount-dwStart;

If (timeout> 1000)

{

Console. WriteLine ("Time Out ");

Recd = true;

}

}

// Close the socket

Socket. Close ();

}

/// <Summary>

/// This method get the Packet and calculates the total size

/// Of the Pack by converting it to byte array

/// </Summary>

Public static Int32 Serialize (IcmpPacket packet,

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.