A Foreign ping program (C #)

Source: Internet
Author: User
Tags array copy header int size socket socket error
Program
//**************************************
//
Name:ping. NET class!
Description:ping a machine from. NET.
This code is CLR compliant.
By:carl Mercier
//
Assumes:the code is a complete consol
e application which can easilly modified
To become Windows Form.
//
This code is copyrighted and has//limited warranties. Please http://
Www.Planet-Source-Code.com/xq/ASP/txtCod
Eid.335/lngwid.10/qx/vb/scripts/showcode
. htm//for details. //**************************************
//

Using System;
Namespace Myping
{
<summary>
Summary description for Class1.
</summary>
Class Myping
{
<summary>
The main entry point for the Applica
tion.
</summary>
Declare some Constant Variables
const int SOCKET_ERROR =-1;
const int Icmp_echo = 8;
[STAThread]
static void Main (string[] args)
{
//
Todo:add code to start Application H
Ere
//
if (args. length==0)
{
If user did not enter no Parameter in
form him
Console.WriteLine ("Usage:myping Console.WriteLine ("Console.WriteLine ("R Optional Switch to Ping the host continuously");
}
else if (args. Length==1)
{
Just the hostname provided by the user
//
Called the "pinghost" and pass th
e HostName as a parameter
Pinghost (Args[0]);
}
else if (args. length==2)
{
The user provided the hostname and the
Switch
if (args[1]== "/R")
{
Loop the ping program
while (true)
{
Called the "pinghost" and pass th
e HostName as a parameter
Pinghost (Args[0]);
}
}
Else
{
If the user provided some other switch
//
Pinghost (Args[0]);
}
}
Else
{
Some Error occured
Console.WriteLine ("Error in Arguments");
}
}
public static void Pinghost (String host)
{
Declare the Iphostentry
System.Net.IPHostEntry Serverhe, Fromhe;
int nbytes = 0;
int dwstart = 0, dwstop = 0;
Initilize a Socket of the Type ICMP
System.Net.Sockets.Socket Socket = new System.Net.Sockets.Socket (System.Net.Sockets.AddressFamily.InterNetwork,
System.Net.Sockets.SocketType.Raw, System.Net.Sockets.ProtocolType.Icmp);
Get the server Endpoint
Try
{
Serverhe = System.Net.Dns.GetHostByName (host);
}
catch (Exception)
{
Console.WriteLine ("Host not Found"); Fail
return;
}
Convert the server ip_endpoint to an
EndPoint
System.Net.IPEndPoint ipepserver = new System.Net.IPEndPoint (serverhe.addresslist[0], 0);
System.Net.EndPoint epserver = (ipepserver);
Set the receiving endpoint to the CLI
ENT machine
Fromhe = System.Net.Dns.GetHostByName (System.Net.Dns.GetHostName ());
System.Net.IPEndPoint ipendpointfrom = new System.Net.IPEndPoint (fromhe.addresslist[0], 0);
System.Net.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 Methos Serialize which counts
The total number of Bytes in the Packe
T
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 ar
Ray
Get the Half size of the Packet
Double double_length = convert.todouble (Index);
Double dtemp = System.Math.Ceiling (DOUBLE_LENGTH/2);
int cksum_buffer_length = Convert.ToInt32 (dtemp);
Create a Byte Array
UInt16 [] Cksum_buffer = new Uint16[cksum_buffer_length];
Code to initilize 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'll return a CHEC
Ksum
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, serial
Ize the packet again
Byte [] sendbuf = new byte[packetsize];
Again check the packet size
Index = Serialize (
Packet
SendBuf,
PacketSize,
Pingdata);
If there is a error in the 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 B
Uffer is the size of the
ICMP header plus the IP header (
TEs
Byte [] Receivebuffer = new byte[256];
nbytes = 0;
Receive the bytes
BOOL RECD =false;
int timeout=0;
loop for checking the Serv
ER 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);
Recd=true;
Break
}
Timeout=system.environment.tickcount-dwstart;
if (timeout>1000)
{
Console.WriteLine ("Time Out");
Recd=true;
}
}
Close the socket
Socket. Close ();
}
public static Int32 Serialize (Icmppacket packet, Byte [] Buffer, Int32 packetsize, Int32 pingdata)
{
Int32 Cbreturn = 0;
Serialize the struct into the 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);
Console.WriteLine ("Serialize type");
//
Array.copy (b_type, 0, Buffer, Index, B_type. Length);
Index + + B_type. Length;
Console.WriteLine ("Serialize Code");
//
Array.copy (b_code, 0, Buffer, Index, B_code. Length);
Index + + B_code. Length;
Console.WriteLine ("Serialize cksum")
//     ;
Array.copy (b_cksum, 0, Buffer, Index, B_cksum. Length);
Index + + b_cksum. Length;
Console.WriteLine ("Serialize id");
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 the data
Array.copy (packet. Data, 0, Buffer, Index, Pingdata);
Index + + Pingdata;
if (Index!= packetsize/* sizeof (icmppacket) * *)
{
Cbreturn =-1;
return cbreturn;
}
Cbreturn = Index;
return cbreturn;
}
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 >>) + (Cksum & 0xFFFF);
Cksum + + (cksum >> 16);
Return (UInt16) (~cksum);
}
}
public class Icmppacket
{
Public Byte type;//Type of message
Public Byte subcode;//type of sub code
Public UInt16 checksum;//ones complement CheckSum of struct
Public UInt16 Identifier; Identifier
Public UInt16 SequenceNumber; Sequence Number
Public Byte [] Data;
}
}


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.