C # Implementation Ping function

Source: Internet
Author: User
Tags bool datetime int size socket
This period of time has been learning C #, has been engaged in the network, or from the implementation of the ping program to write it.
The method of calling Ping is as follows:
Ping mping=new Ping ();
Mping.pinging ("127.0.0.1", 255,65535);
Mping.receive (); Successfully received return True,timeout return False
All source code is as follows:
Using System;
Using System.IO;
Using System.Net;
Using System.Net.Sockets;
Namespace Ping
{
<summary>
Summary description for Ping.
</summary>
///
//
//
IP Header
public class Iphdr
{
Public byte VIHL
{
Get{return MVIHL;}
Set{mvihl=value;}
}private byte Mvihl;
Public byte TOS
{
Get{return MTOs;}
Set{mtos=value;}
}private byte MTOs;
public short Totlen
{
Get{return Mtotlen;}
Set{mtotlen=value;}
}private short Mtotlen;
public short ID
{
Get{return MID;}
Set{mid=value;}
}private short MID;
public short Flagoff
{
Get{return Mflagoff;}
Set{mflagoff=value;}
}private short Mflagoff;
Public byte TTL
{
Get{return Mttl;}
Set{mttl=value;}
}private byte Mttl;
Public byte Protocol
{
Get{return Mprotocol;}
Set{mprotocol=value;}
}private byte Mprotocol;
Public ushort Checksum
{
Get{return Mchecksum;}
Set{mchecksum = value;}
}private ushort Mchecksum;
Public ULONG IASRC
{
Get{return miasrc;}
Set{miasrc=value;}
}private ULONG Miasrc;
Public ULONG IADST
{
Get{return MIADST;}
Set{miadst=value;}
}private ULONG MIADST;

public static string address (ulong obj)
{
byte s1= (byte) obj;
byte s2= (Byte) (obj>>8);
byte s3= (Byte) (obj>>16);
byte s4= (Byte) (obj>>24);
Return String.Format ("{0}.{ 1}. {2}. {3} ", S1,S2,S3,S4);//s1+". " +s2+ "." +s3+ "." +S4;
}
public void Encode (BinaryWriter writer)
{
Writer. Write (VIHL);
Writer. Write (TOS);
Writer. Write ((Int16) totlen);
Writer. Write ((Int16) ID);
Writer. Write ((Int16) flagoff);
Writer. Write (TTL);
Writer. Write (Protocol);
Writer. Write ((UInt16) Checksum);
Writer. Write ((UInt32) iasrc);
Writer. Write ((UInt32) IADST);

}
public void Decode (BinaryReader reader)
{
Vihl=reader. ReadByte ();
Tos=reader. ReadByte ();
Totlen=reader. ReadInt16 ();
Id=reader. ReadInt16 ();
Flagoff=reader. ReadInt16 ();
Ttl=reader. ReadByte ();
Protocol=reader. ReadByte ();
Checksum=reader. ReadUInt16 ();
Iasrc=reader. ReadUInt32 ();
Iadst=reader. ReadUInt32 ();
}

}
ICMP Header;
public class Icmphdr
{
Public byte Type
{
Get{return Mtype;}
Set{mtype=value;}
}private byte Mtype;
Public byte Code
{
Get{return Mcode;}
Set{mcode=value;}
}private byte mcode=0;
Public ushort Checksum
{
Get{return Mchecksum;}
Set{mchecksum=value;}
}private ushort Mchecksum=0;
Public ushort ID
{
Get{return MID;}
Set{mid=value;}
}private ushort MID;
Public ushort Seq
{
Get{return Mseq;}
Set{mseq=value;}
}private ushort Mseq;
Public ULONG Tmsend
{
Get{return Mtmsend;}
Set{mtmsend=value;}
}private ULONG Mtmsend;

public int Ntaskid
{
Get{return Mntaskid;}
Set{mntaskid=value;}
}private int mntaskid;
public void Encode (BinaryWriter writer)
{
Writer. Write (Type);
Writer. Write (Code);
Writer. Write ((UInt16) Checksum);
Writer. Write ((UInt16) ID);
Writer. Write ((UInt16) Seq);
Writer. Write ((UInt32) tmsend);
Writer. Write (Ntaskid);
}
public void Decode (BinaryReader reader)
{
Type=reader. ReadByte ();
Code=reader. ReadByte ();
Checksum=reader. ReadUInt16 ();
Id=reader. ReadUInt16 ();
Seq=reader. ReadUInt16 ();
Tmsend=reader. ReadUInt32 ();
Ntaskid=reader. ReadInt32 ();
}
Public UINT Sum ()
{
UINT Sum=0;
Sum + = (ushort) (type+ (code<<8));
Sum + = (ushort) ID;
Sum + = (ushort) Seq;
Sum + = (ushort) tmsend;
Sum + = (ushort) (tmsend>>16);
Sum + = (ushort) ntaskid;
Sum + = (ushort) (ntaskid>>16);
return sum;
}
}
public class Echorequest
{
Private char[] Mchar;
Public Icmphdr icmp=new ICMPHDR ();
Public echorequest (int size,char NChar)
{
Mchar=new Char[size];
for (int i=0;i<size;i++)
Mchar[i]=nchar;
}
public void Encode (BinaryWriter writer)
{
Chksum ();
Icmp. Encode (writer);
Writer. Write (Mchar);
}
/* public void Decode (BinaryReader reader)
{
Icmp. Decode (reader);
String S=reader. ReadString ();
Mchar=s.tochararray ();
}
* private void Chksum ()
{
UINT SUM=ICMP. Sum ();
for (int i=0;i<mchar.length;i+=2)
Sum + = (ushort) (mchar[i]+ (mchar[i+1]<<8));
//
sum = (sum >>) + (sum & 0xFFFF); Add hi to Low 16
sum + = (sum >> 16); Add Carry
Short answer = (short) ~sum; Truncate to Bits
Icmp. checksum= (ushort) answer;
}
}
ICMP Echo Reply
public class Echoreply
{
Public IPHDR Iphdr=null;
Public ICMPHDR Icmphdr=null;
Public char[] Cfiller;
public void Decode (BinaryReader reader)
{
Iphdr=new Iphdr ();
Iphdr.decode (reader);

Icmphdr=new Icmphdr ();
Icmphdr.decode (reader);

int bytes= (int) reader. Basestream.length;
Cfiller=reader. ReadChars (8);
Cfiller=reader. ReadChars (bytes-36);
}
}
public class StateObject
{
Public Socket worksocket = null; Client socket.
public const int buffersize = 256; Size of receive buffer.
Public byte[] buffer = new Byte[buffersize]; Receive buffer.
Public StringBuilder sb = new StringBuilder ();//Received data string.
}

public class Ping
{
Socket Socket=null;
int m_id;
UINT M_taskid;
UINT M_seq;
System.Threading.ManualResetEvent Recvdone=null;
DateTime M_dtsend;
Public Ping ()
{
m_seq=0;
Recvdone=new System.Threading.ManualResetEvent (FALSE);
Socket=new Socket (ADDRESSFAMILY.INTERNETWORK,SOCKETTYPE.RAW,PROTOCOLTYPE.ICMP);
//
Todo:add constructor Logic here
//
}
public bool Pinging (string Addr,int ID, uint taskid)
{
Try
{
M_id=id;
M_taskid=taskid;
Byte[] Byreq =fillechoreq ();

Send To

IPEndPoint LEP = new IPEndPoint (ipaddress.parse (addr), 0);


Socket. SendTo (BYREQ,LEP);
}
catch (Exception e)
{
Console.WriteLine ("Send Error:" +e.tostring ());
return false;
}

return true;
}
Private byte[] Fillechoreq ()
{
m_seq++;
if (m_seq>1000)
M_seq=1;
Echorequest req=new echorequest (8, ' E ');
req.icmp.type=8;
req.icmp.code=0;
Req.icmp.id= (ushort) m_id;
Req.icmp.seq= (ushort) m_seq;
req.icmp.ntaskid= (int) m_taskid;
M_dtsend=datetime.now;

req.icmp.tmsend= (ULONG) DateTime.Now.Ticks;
MemoryStream stream=new MemoryStream ();
BinaryWriter writer=new BinaryWriter (stream);
Req. Encode (writer);

int toreads= (int) stream. Length;
Get Byte Array.
Byte[] Byreq=stream. ToArray ();

Stream. Close ();
return byreq;
}

private static UINT Iocntlcheck (Socket s)
{

Set up the input and output byte arrays.
byte[] Invalue = bitconverter.getbytes (0);
byte[] Outvalue = bitconverter.getbytes (0);

Check How many bytes have been received.
S.iocontrol (0x4004667f, Invalue, Outvalue);
UINT Bytesavail = Bitconverter.touint32 (outvalue, 0);
return bytesavail;
}
Used to check reply data by sync
public bool Checkreply ()
{
UINT Byavail=iocntlcheck (socket);
if (byavail<=0)
return false;
Try
{
Byte[] Recv=new Byte[byavail];
Socket. Receive (recv);
Return Checkechoreply (recv, (int) byavail);
}
catch (Exception e)
{
Console.WriteLine (E.tostring ());
return false;
}
}
Directly analyze the byte array.

public bool CheckEchoReply1 (byte[] Recv,int len)
{
if (len<36)
return false;
int ttl=recv[8];
String src=recv[12]+ "." +recv[13]+ "." +recv[14]+ "." +RECV[15];
String dst=recv[16]+ "." +recv[17]+ "." +recv[18]+ "." +RECV[19];
int type=recv[20];
if (type!=0)
return false;
24,25, ID
int id=recv[24]+ (RECV[25]&LT;&LT;8);
if (ID!=m_id)
return false;
26,27, seq
int seq=recv[26]+ (RECV[27]&LT;&LT;8);
32,33,34,35, Task ID
int taskid=recv[32]+ (RECV[33]&LT;&LT;8) + (recv[34]<<16) + (recv[35]<<24);
if (TaskID!=m_taskid)
return false;
int bytes= len-36;


TimeSpan Ts=datetime.now-m_dtsend;
Console.WriteLine ("Reply from {0}: Bytes={1},icmp_seq={2},ttl={3},time={4} MS",
Src,bytes,seq,ttl, Ts.milliseconds);

return true;

}
Use IPHDR and ICMPHDR to analyze Replyk data.
public bool Checkechoreply (byte[] Recv,int len)
{
20bytes IP Pack.
if (len<36)
return false;
MemoryStream stream=new MemoryStream (recv,0,len,false);
BinaryReader reader=new BinaryReader (stream);
Echoreply reply=new echoreply ();
Reply. Decode (reader);

Stream. Close ();
String dst,src;
Dst=iphdr. Address (REPLY.IPHDR.IADST);
Src=iphdr. Address (REPLY.IPHDR.IASRC);

Type
BYTE Type=reply.icmphdr.type;
24,25 ID
int id=reply.icmphdr.id;
26,27,seq
int seq=reply.icmphdr.seq;
//

int bytes= len-36;

32,33,34,35, Task ID
DateTime dt=new datetime ((long) reply.icmpHdr.tmSend);
Consdt.tostring ();
UINT taskid= (UINT) reply.icmphdr.ntaskid;//(UINT) (recv[32]+ (recv[33]<<8) + (recv[34]<<16) + (recv[35) &LT;&LT;24));
TimeSpan Ts=datetime.now-m_dtsend;//dt;
if (type = = 0 && id = m_id && m_taskid==taskid)
{
Console.WriteLine ("Reply from {0}: Bytes={1},icmp_seq={2},ttl={3},time={4} MS",
Src,bytes,seq,reply.iphdr.ttl, Ts.milliseconds);

return true;
}
Else
{
Console.WriteLine ("Unknown data,{0},{1},type={2},icmp_seq={3}",
SRC,DST,TYPE,SEQ);
}
return false;

}
public bool Receive ()
{
Try
{
Recvdone.reset ();
StateObject so=new stateobject ();
So.worksocket=socket;

Socket. SetSocketOption (socketoptionlevel.socket,socketoptionname.receivetimeout,5000);

IPEndPoint sender = new IPEndPoint (ipaddress.any, 0);
EndPoint tempremoteep = (EndPoint) sender;

Socket. Beginreceivefrom (So.buffer,0,stateobject.buffersize,0,ref tempremoteep,new AsyncCallback (ReceiveCallBack), so);

if (!recvdone.waitone ())//. WaitOne (1000,false))
{//receive timeout
Console.WriteLine ("Request timed out");
return false;
}

}
catch (Exception e)
{
Console.WriteLine ("Fail,{0}", e.tostring ());
return false;
}
return true;
}
public void ReceiveCallback (IAsyncResult ar)
{
Try
{
StateObject obj= (stateobject) ar. asyncstate;
Socket Sock=obj.worksocket;
IPEndPoint ep=new IPEndPoint (ipaddress.any,0);
EndPoint tempep= (EndPoint) EP;
int Recvs=sock. Endreceivefrom (Ar,ref Tempep);
if (checkechoreply (OBJ.BUFFER,RECVS))
Recvdone.set ();
Else
Sock. Beginreceivefrom (Obj.buffer,0,stateobject.buffersize,0,ref tempep,new AsyncCallback (receiveCallBack), obj);
Console.WriteLine ("Address:{0}", (IPEndPoint) TEMPEP). address);
}
catch (Exception e)
{
Console.WriteLine ("CallBack Error:" +e.tostring ());

}
}
public void Clear ()
{
Socket. Close ();
}
}
}




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.