/// <summary> /// Convert Icmp package to array of bytes /// </summary> /// <param name="package"></param> /// <returns>Array of bytes</returns> public byte[] PackageToByteArray(IcmpPackage package) { byte[] data = new byte[package.MessageSize + 9]; Buffer.BlockCopy(BitConverter.GetBytes(package.Type), 0, data, 0, 1); Buffer.BlockCopy(BitConverter.GetBytes(package.Code), 0, data, 1, 1); Buffer.BlockCopy(BitConverter.GetBytes(package.Checksum), 0, data, 2, 2); Buffer.BlockCopy(package.Message, 0, data, 4, package.MessageSize); return(data); }
/// <summary> /// Convert array of bytes to Icmp package /// </summary> /// <param name="data"></param> /// <param name="size"></param> /// <returns>Icmp Package</returns> public IcmpPackage ByteArrayToPackage(byte[] data, int size) { IcmpPackage package = new IcmpPackage { Type = data[20], Code = data[21], Checksum = BitConverter.ToUInt16(data, 22), MessageSize = size - 24 }; Buffer.BlockCopy(data, 24, package.Message, 0, package.MessageSize); return(package); }
public static void Main(string[] argv) { var remoteIPs = Dns.GetHostAddresses("www.google.com"); IPEndPoint ipEndPoint = new IPEndPoint(remoteIPs[0], 0); EndPoint endPoint = (EndPoint)ipEndPoint; IcmpPackageBuilder icmpBuilder = new IcmpPackageBuilder(); IcmpPackage icmpPackage = icmpBuilder.Build(); Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.Icmp); socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 3000); icmpPackage.Checksum = icmpBuilder.CalculateChecksum(icmpPackage); socket.SendTo(icmpBuilder.PackageToByteArray(icmpPackage), ipEndPoint); int recv; byte[] data = new byte[1024]; try { recv = socket.ReceiveFrom(data, ref endPoint); } catch (SocketException e) { Console.WriteLine(e.Message); Console.ReadLine(); return; } Console.WriteLine("Response from: {0}", endPoint.ToString()); Console.WriteLine(" Type {0}", responsePackage.Type); Console.WriteLine(" Code: {0}", responsePackage.Code); int Sequence = BitConverter.ToInt16(responsePackage.Message, 2); Console.WriteLine(" Identifier: {0}", responsePackage.Id); Console.WriteLine(" Sequence: {0}", Sequence); string stringData = Encoding.ASCII.GetString(responsePackage.Message, 4, responsePackage.MessageSize - 4); Console.WriteLine(" Data: {0}", stringData); Console.ReadLine(); socket.Close(); }
public UInt16 CalculateChecksum(IcmpPackage package) { UInt32 chcksm = 0; byte[] data = this.PackageToByteArray(package); int packetsize = package.MessageSize + 8; int index = 0; while (index < packetsize) { chcksm += Convert.ToUInt32(BitConverter.ToUInt16(data, index)); index += 2; } chcksm = (chcksm >> 16) + (chcksm & 0xffff); chcksm += (chcksm >> 16); return((UInt16)(~chcksm)); }