C # implementation ping function

xiaoxiao2021-03-19  218

The calling method is as follows: ping mping = new ping (); MPING.PINGING ("127.0.0.1", 255, 65535); MPING.Receive (); // Successfully Receive Returns True, TIMEOUT Returns all source code as follows: Using system; using system.net; using system.net.sockets; namespace ping {///

/// summary description for ping. /// /// // / / / // ip header public class iphdr {public byte vihl {get {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;} set {mchecksum = value;}} private ushort mchecksum; public ul ong 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); 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) adst);} 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 class ket {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 {mid = value;}} private usrth 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;}} privacy INT MNTASKID; public void encode (binarywriter writer) {Writer.write (Type); Writer.write (CODE); Writer.Write ((uint16) checksum); Writer.write ((UINT16) ID); Writer.write UINT16); 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}} 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 > 16) (SUM & 0xFFFF); // Add Hi 16 to LOW 16 SUM = (SUM >> 16) ; // add carry short answer = (short) ~ sum; // truncate to 16 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 (READE R); ICMPHDR = New ICMphdr (); ICMphDr.Decode (osc); 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 task) {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 botte [] 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_dsend = DateTime.now; Req. ICMP.TMSEND = (ulong) DateTime.now.ticks; memorystream stream = new memorystream (); binarywriter write = new binarywriter; req.encode (write); int ToreAds = (int)) Tream.length; // Get Byte Array. Byte [] byreq = stream.toArray (); stream.close (); return byreq;} private static uint ocntlcheck (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 [] rv, 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]; ​​intv [19]; ​​int TYPE = Recv [20]; if (Type! = 0) Return False; // 24, 25, ID INT ID = Recv [24] (Recv [25] << 8); if (id! = m_id) Return False; // 26, 27, seq int SEQ = Recv [26] (Recv [27] << 8); // 32, 33, 34, 35, Task ID INT Taskid = Rec [32] (Recv [ << 8) (Recv [34] << 16) (RECV [35] << 24); if (taskid! = M_taskid) Return False; int Bytes = LEN-36; Timespan TS = DateTime.now -m_dtend; 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, icmphdr to analyze replyk data. Public bool checkechoreply (Byte [] RECV, INT LEN) {// 20bytes IP Pack. IF (Len <36) Return False; ME moryStream 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 in = reply.icphdr .Id; // 26, 27, seq int seq = reply.icphdr.seq; // int reference = len-36; // 32, 33, 34, 35, Task ID DateTime DT = New DateTime ((long) reply .icphdr.tmsend;

// condt.tostring (); uint taskid = (uint) reply.icphdr.ntaskid; // (UINT) (RECV [32] (Recv [33] << 8) (Recv [34] << 16) (Recv [35] << 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);} returnaf 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 Fal Se;}} catch (exception e) {console.writeline ("fail, {0}", e.tostring ()); return false;} return true;} public void receivers {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}"

转载请注明原文地址:https://www.9cbs.com/read-130235.html

New Post(0)