C # implementation ping function

xiaoxiao2021-03-06  48

During this time, I have been learning C #. I used to engage in the network. It is still written from the implementation of the PING program. The calling method is as follows: ping mping = new ping (); MPING.PINGING ("127.0.0.1", 255, 65535); MPING.Receive (); // Successfully received Return true, Timeout Returns all source code as follows: use system; using system.io; use system.net; using system.net.sockets; namespace ping {//////

/// Summary Description for ping. ///////////////ww 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 {mProtocol = value;}} private byte mProtocol; Public Ushort chort ecksum {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); 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 write) {Writer.write (vihl); 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 ); 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 > 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 (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 ipndpoint 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 bote [] 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 = (usort) m_seq; Req.icmp.ntaskid = (int) m_taskid; m_dtend = 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 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) (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] << 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 = RECV [32] (Recv [33] << 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;.. 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.icphdr.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 taski = (uint) reply.icphdr.ntaskid; // (UINT) (RECV [32] (Recv [33] << 8) (Recv [34] << 16) (RECV [35] << 24)); Timespan Ts = DateTime.now -m_dtend; / / 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 iPadpoint (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"; returnaf 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} ", (ipndpoint) tempep) .address);} catch (Exception E) {Console.Writeline (" Callback Error: " E.TOString ());}} public void clear ()} public void clear () {socket.close ();}}} Huh, it is simple, you can copy the code first, try it yourself, you can talk about it, email / msn: wugy006 # 163.Net

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

New Post(0)