Ping demo program

Source: Internet
Author: User

Using System;
Using System. Drawing;
Using System. Collections;
Using System. ComponentModel;
Using System. Windows. Forms;
Using System. Data;
Using System. Net;
Using System. Net. Sockets;

Namespace Ping
{
/// <Summary>
/// Summary of Form1.
/// </Summary>
///

Public class Form1: System. Windows. Forms. Form
{
* ****** System. Windows. Forms. Label label1;
* ****** System. Windows. Forms. TextBox textBox1;
* ****** System. Windows. Forms. Button button1;
* ***** System. Windows. Forms. RichTextBox richTextBox1;
/// <Summary>
/// Required designer variables.
/// </Summary>
* ****** System. ComponentModel. Container components = null;

Public Form1 ()
{
//
// Required for Windows Form Designer support
//
InitializeComponent ();

//
// TODO: add Any constructor code after InitializeComponent calls
//
}

/// <Summary>
/// Clear all resources in use.
/// </Summary>
Protected override void Dispose (bool disposing)
{
If (disposing)
{
If (components! = Null)
{
Components. Dispose ();
}
}
Base. Dispose (disposing );
}

# Region code generated by Windows Form Designer
/// <Summary>
/// The designer supports the required methods-do not use the code editor to modify
/// Content of this method.
/// </Summary>
* ****** Void InitializeComponent ()
{
This. label1 = new System. Windows. Forms. Label ();
This. textBox1 = new System. Windows. Forms. TextBox ();
This. button1 = new System. Windows. Forms. Button ();
This. richTextBox1 = new System. Windows. Forms. RichTextBox ();
This. SuspendLayout ();
//
// Label1
//
This. label1.Location = new System. Drawing. Point (8, 16 );
This. label1.Name = "label1 ";
This. label1.Size = new System. Drawing. Size (80, 16 );
This. label1.TabIndex = 0;
This. label1.Text = "Target Host Name :";
//
// TextBox1
//
This. textBox1.Location = new System. Drawing. Point (96, 16 );
This. textBox1.Name = "textBox1 ";
This. textBox1.Size = new System. Drawing. Size (152, 21 );
This. textBox1.TabIndex = 1;
This. textBox1.Text = "127.0.0.1 ";
//
// Button1
//
This. button1.Location = new System. Drawing. Point (256, 16 );
This. button1.Name = "button1 ";
This. button1.Size = new System. Drawing. Size (96, 23 );
This. button1.TabIndex = 2;
This. button1.Text = "Ping ";
This. button1.Click + = new System. EventHandler (this. button#click );
//
// RichTextBox1
//
This. richTextBox1.Location = new System. Drawing. Point (8, 48 );
This. richTextBox1.Name = "richTextBox1 ";
This. richTextBox1.Size = new System. Drawing. Size (344,184 );
This. richTextBox1.TabIndex = 3;
This. richTextBox1.Text = "";
//
// Form1
//
This. AutoScaleBaseSize = new System. Drawing. Size (6, 14 );
This. ClientSize = new System. Drawing. Size (360,238 );
This. Controls. Add (this. richTextBox1 );
This. Controls. Add (this. button1 );
This. Controls. Add (this. textBox1 );
This. Controls. Add (this. label1 );
This. MaximizeBox = false;
This. Name = "Form1 ";
This. StartPosition = System. Windows. Forms. FormStartPosition. CenterScreen;
This. Text = "show PING ";
This. ResumeLayout (false );

}
# Endregion

/// <Summary>
/// Main entry point of the application.
/// </Summary>
[STAThread]
Static void Main ()
{
Application. Run (new Form1 ());
}
// Declare a constant
Const int SOCKET_ERROR =-1;
Const int ICMP_ECHO = 8;
Public static Int32 Serialize (IcmpPacket packet, Byte [] Buffer, Int32 PacketSize, Int32 PingData)
{// Get the packet content, convert it to a byte array, and then calculate the packet length
Int32 cbReturn = 0;
// Convert the datagram structure to an array
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 );
Array. Copy (B _type, 0, Buffer, Index, B _type.Length );
Index + = B _type.Length;
Array. Copy (B _code, 0, Buffer, Index, B _code.Length );
Index + = B _code.Length;
Array. Copy (B _cksum, 0, Buffer, Index, B _cksum.Length );
Index + = B _cksum.Length;
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;
// Copy data
Array. Copy (packet. Data, 0, Buffer, Index, PingData );
Index + = PingData;
If (Index! = PacketSize/* sizeof (IcmpPacket )*/)
{
CbReturn =-1;
Return cbReturn;
}
Cbreturn = index;
Return cbreturn;
}
/// <Summary>
/// Checksum Algorithm
/// </Summary>
Public static uint16 checksum (uint16 [] buffer, int size)
{
Int32 cksum = 0;
Int counter;
Counter = 0;
/* Accumulate the ICMP header binary data in 2 bytes */
While (size> 0)
{
Uint16 val = buffer [Counter];
Cksum + = convert. toint32 (buffer [Counter]);
Counter + = 1;
Size-= 1;
}
/* If the ICMP header is an odd number of bytes, the last byte is left. Consider the last byte as
* The high byte of the 2-byte data. The low byte of the 2-byte data is 0. continue to accumulate */
Cksum = (cksum> 16) + (cksum & 0 xffff );
Cksum + = (cksum> 16 );
Return (UInt16 )(~ Cksum );
}
* ****** Void button#click (object sender, System. EventArgs e)
{// PING
This. richTextBox1.Text = "";
For (int p = 0; p <10; p ++)
{
Try
{
String HostName = this. textBox1.Text;
Int nbytes = 0;
Int dwstart = 0, dwstop = 0;
// Initialize an ICMP socket
Socket socket = new socket (addressfamily. InterNetwork, sockettype. Raw, protocoltype. ICMP );
// Obtain the host name of the target host
Iphostentry serverhe = DNS. gethostbyname (hostname );
Ipendpoint ipepserver = new ipendpoint (serverhe. Addresslist [0], 0 );
Endpoint epserver = (ipepserver );
Iphostentry fromhe = DNS. gethostbyname (DNS. gethostname ());
Ipendpoint ipendpointfrom = new ipendpoint (fromhe. Addresslist [0], 0 );
EndPoint EndPointFrom = (ipEndPointFrom );
Int PacketSize = 0;
IcmpPacket packet = new IcmpPacket ();
// Construct a Datagram
Packet. Type = ICMP_ECHO;
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];
// Initialize Packet. Data
For (INT I = 0; I <pingdata; I ++)
{
Packet. Data [I] = (byte )'#';
}
// Save the length of the datagram
Packetsize = pingdata + 8;
Byte [] icmp_pkt_buffer = new byte [packetsize];
Int32 Index = 0;
// Call the serialize Method
// Total number of bytes
Index = serialize (
Packet,
Icmp_pkt_buffer,
Packetsize,
PingData );
If (Index =-1)
{
This. richTextBox1.Text + = "The message size is incorrect! \ N ";
Return;
}
// Convert it to an array of the Uint16 type and obtain half of the datagram Length
Double double_length = Convert. ToDouble (Index );
Double dtemp = Math. Ceiling (double_length/2 );
Int cksum_buffer_length = Convert. ToInt32 (dtemp );
// Generate a byte array
UInt16 [] cksum_buffer = new UInt16 [cksum_buffer_length];
// Initialize the Uint16 type 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 checksum to return the check and
UInt16 u_cksum = checksum (cksum_buffer, cksum_buffer_length );
// Check and message
Packet. CheckSum = u_cksum;
Byte [] sendbuf = new Byte [PacketSize];
// Check the packet size again
Index = Serialize (
Packet,
Sendbuf,
PacketSize,
PingData );
// Report an error if any.
If (Index =-1)
{
This. richTextBox1.Text + = "The message size is incorrect! \ N ";
Return;
}
DwStart = System. Environment. TickCount; // start time
// Send a datagram using socket
If (nbytes = socket. sendto (sendbuf, packetsize, 0, epserver) = socket_error)
{
This. richtextbox1.text + = "data packets cannot be sent! \ N ";
}
// Initialize the buffer. Accept the buffer
// ICMP header + IP header (20 bytes)
Byte [] receivebuffer = new byte [1, 256];
Nbytes = 0;
// Accept byte streams
Bool recd = false;
Int timeout = 0;
// Cyclically check the response time of the target host
While (! Recd)
{
NBytes = socket. ReceiveFrom (ReceiveBuffer, 256, 0, ref EndPointFrom );
If (nBytes = SOCKET_ERROR)
{
This. richTextBox1.Text + = "the target host has no response! \ N ";
Recd = true;
Break;
}
Else if (nBytes> 0)
{
DwStop = System. Environment. TickCount-dwStart;
This. richTextBox1.Text + = "data from host:" + this. textBox1.Text + ", number of received Bytes:" + nBytes + ", time consumed:" + dwStop + "ms \ n ";
Recd = true;
Break;
}
Timeout = System. Environment. TickCount-dwStart;
If (timeout> 1000)
{
This. richTextBox1.Text + = "connection timeout! \ N ";
Recd = true;
}
}
// Close the socket
Socket. Close ();
}
Catch (Exception Err)
{
MessageBox. Show ("failed to PING the target host! Error Message: "+ Err. Message," Message prompt ", MessageBoxButtons. OK, MessageBoxIcon. Information );
Return;
}
}
}
}
Public class IcmpPacket
{
Public Byte Type; // Message Type
Public Byte SubCode; // SubCode type
Public UInt16 CheckSum; // checking and
Public UInt16 Identifier; // Identifier
Public UInt16 SequenceNumber; // sequence number
Public Byte [] Data; // Data
} // ICMP Packet
}
 

// Note: * ********** is p rivate.

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.