private static unsafe byte[] CreateSendMessageBuffer(IpHeader ipHeader, IcmpHeader icmpHeader, byte[] payload) { int icmpHeaderSize = sizeof(IcmpHeader); int offset = 0; int packetSize = ipHeader.TotalLength != 0 ? ipHeader.TotalLength : checked (icmpHeaderSize + payload.Length); byte[] result = new byte[packetSize]; if (ipHeader.TotalLength != 0) { int ipHeaderSize = sizeof(IpHeader); new Span <byte>(&ipHeader, sizeof(IpHeader)).CopyTo(result); offset = ipHeaderSize; } //byte[] result = new byte[headerSize + payload.Length]; Marshal.Copy(new IntPtr(&icmpHeader), result, offset, icmpHeaderSize); payload.CopyTo(result, offset + icmpHeaderSize); // offset now still points to beginning of ICMP header. ushort checksum = ComputeBufferChecksum(result.AsSpan(offset)); // Jam the checksum into the buffer. result[offset + 2] = (byte)(checksum >> 8); result[offset + 3] = (byte)(checksum & (0xFF)); return(result); }
private static bool readNetworkHeaders(BinaryReader binaryReader) { EthernetHeader ethernetHeader = EthernetHeader.read(binaryReader); // Skip non-IP packets if (ethernetHeader.proto != 8) { throw new InvalidDataException(); } IpHeader ipHeader = IpHeader.read(binaryReader); // Skip non-UDP packets if (ipHeader.proto != 17) { throw new InvalidDataException(); } UdpHeader udpHeader = UdpHeader.read(binaryReader); bool isSend = (udpHeader.dPort >= 9000 && udpHeader.dPort <= 9013); bool isRecv = (udpHeader.sPort >= 9000 && udpHeader.sPort <= 9013); // Skip non-AC-port packets if (!isSend && !isRecv) { throw new InvalidDataException(); } return(isSend); }
private unsafe SocketConfig GetSocketConfig(IPAddress address, byte[] buffer, int timeout, PingOptions?options) { // Use a random value as the identifier. This doesn't need to be perfectly random // or very unpredictable, rather just good enough to avoid unexpected conflicts. ushort id = (ushort)Random.Shared.Next(ushort.MaxValue + 1); IpHeader iph = default; bool ipv4 = address.AddressFamily == AddressFamily.InterNetwork; bool sendIpHeader = ipv4 && options != null && SendIpHeader; if (sendIpHeader) { iph.VersionAndLength = 0x45; // On OSX this strangely must be host byte order. iph.TotalLength = (ushort)(sizeof(IpHeader) + checked (sizeof(IcmpHeader) + buffer.Length)); iph.Protocol = 1; // ICMP iph.Ttl = (byte)options !.Ttl; iph.Flags = (ushort)(options.DontFragment ? 0x4000 : 0); #pragma warning disable 618 iph.DestinationAddress = (uint)address.Address; #pragma warning restore 618 // No need to fill in SourceAddress or checksum. // If left blank, kernel will fill it in - at least on OSX. } return(new SocketConfig( new IPEndPoint(address, 0), timeout, options, ipv4, ipv4 ? ProtocolType.Icmp : ProtocolType.IcmpV6, id, CreateSendMessageBuffer(iph, new IcmpHeader() { Type = ipv4 ? (byte)IcmpV4MessageType.EchoRequest : (byte)IcmpV6MessageType.EchoRequest, Identifier = id, }, buffer))); }
private void ReceiveCallback(IAsyncResult ar) { var currentTime = _pingStopwatch.ElapsedTicks; var elapsedTime = 0; var bytesRead = _socket.EndReceive(ar); if (ar.AsyncState is byte[] buffer) { var ipHeader = new IpHeader(buffer, bytesRead); if (ipHeader.ProtocolType == ProtocolType.Icmp && !_receivedIps.ContainsKey(ipHeader.RawSourceAddress)) { UpdateLastResult(); _receivedIps[ipHeader.RawSourceAddress] = true; var icParsed = new IcmpPacket(ipHeader.Data, ipHeader.MessageLength); if (MeasureTime) { // ReSharper disable once AssignNullToNotNullAttribute var parsedTime = BitConverter.ToInt64(icParsed.Data.Array, icParsed.Data.Offset); elapsedTime = TimeSpan.FromTicks(currentTime - parsedTime).Milliseconds; } var pingReplyObject = TypeHelper.Construct <PingReply>(buffer, bytesRead, ipHeader.SourceAddress, elapsedTime); var pingCompletedArgs = TypeHelper.Construct <PingCompletedEventArgs>(pingReplyObject, new Exception(), false, this); OnResult?.Invoke(this, pingCompletedArgs); } } }
public virtual void Parse(byte[] source, ref int index) { IpHeader.Parse(source, ref index); IcmpPacket = CreatePacket(source, index); try { IcmpPacket.Parse(source, ref index); } catch (Exception) { IcmpPacket = null; throw; } }
public static IpHeader read(BinaryReader binaryReader) { IpHeader newObj = new IpHeader(); newObj.verIhl = binaryReader.ReadByte(); newObj.tos = binaryReader.ReadByte(); newObj.tLen = binaryReader.ReadUInt16(); newObj.identification = binaryReader.ReadUInt16(); newObj.flagsFo = binaryReader.ReadUInt16(); newObj.ttl = binaryReader.ReadByte(); newObj.proto = binaryReader.ReadByte(); newObj.crc = binaryReader.ReadUInt16(); newObj.sAddr = IpAddress.read(binaryReader); newObj.dAddr = IpAddress.read(binaryReader); return(newObj); }
public void TestUnrolling() { var a = Arbitrary <bool>(); var b = Arbitrary <bool>(); var x = Arbitrary <int>(); var y = Arbitrary <int>(); var byte1 = Arbitrary <byte>(); var byte2 = Arbitrary <byte>(); var short1 = Arbitrary <short>(); var short2 = Arbitrary <short>(); var ushort1 = Arbitrary <ushort>(); var ushort2 = Arbitrary <ushort>(); var uint1 = Arbitrary <uint>(); var uint2 = Arbitrary <uint>(); var long1 = Arbitrary <long>(); var long2 = Arbitrary <long>(); var ulong1 = Arbitrary <ulong>(); var ulong2 = Arbitrary <ulong>(); var bigint1 = Arbitrary <BigInteger>(); var bigint2 = Arbitrary <BigInteger>(); var string1 = Arbitrary <string>(); var string2 = Arbitrary <string>(); var string3 = Arbitrary <string>(); var list1 = Arbitrary <IList <byte> >(); var list2 = Arbitrary <IList <byte> >(); var h1 = Arbitrary <IpHeader>(); var h2 = Arbitrary <IpHeader>(); var opt = Arbitrary <Option <int> >(); var arg = new ZenArgumentExpr <int>(); var header = IpHeader.Create(Ip.Create(1), Ip.Create(2), 3, 4, 5); CheckEqual(True(), True()); CheckEqual(False(), False()); CheckEqual(And(a, b), And(a, b)); CheckEqual(Or(a, b), Or(a, b)); CheckEqual(Not(a), Not(a)); CheckEqual(x | y, x | y); CheckEqual(x & y, x & y); CheckEqual(x ^ y, x ^ y); CheckEqual(x + y, x + y); CheckEqual(~x, ~x); CheckEqual(byte1 + byte2, byte1 + byte2); CheckEqual(short1 + short2, short1 + short2); CheckEqual(ushort1 + ushort2, ushort1 + ushort2); CheckEqual(uint1 + uint2, uint1 + uint2); CheckEqual(long1 + long2, long1 + long2); CheckEqual(ulong1 + ulong2, ulong1 + ulong2); CheckEqual(x - y, x - y); CheckEqual(x * y, x * y); CheckEqual(x < y, x < y); CheckEqual(x > y, x > y); CheckEqual(x <= y, x <= y); CheckEqual(x >= y, x >= y); CheckEqual(bigint1 + bigint2, bigint1 + bigint2); CheckEqual(string1 + string2, string1 + string2); CheckEqual(string1.At(bigint1), string1.At(bigint1)); CheckEqual(string1.Contains(string2), string1.Contains(string2)); CheckEqual(string1.StartsWith(string2), string1.StartsWith(string2)); CheckEqual(string1.EndsWith(string2), string1.EndsWith(string2)); CheckEqual(string1.IndexOf(string2, bigint1), string1.IndexOf(string2, bigint1)); CheckEqual(string1.Length(), string1.Length()); CheckEqual(string1.ReplaceFirst(string2, string3), string1.ReplaceFirst(string2, string3)); CheckEqual(string1.Substring(bigint1, bigint2), string1.Substring(bigint1, bigint2)); CheckEqual(opt.HasValue(), opt.HasValue()); CheckEqual(arg, arg); CheckEqual(If(a, x, y), If(a, x, y)); CheckEqual(header, header); CheckEqual(header.WithField("DstIp", Ip.Create(99)), header.WithField("DstIp", Ip.Create(99))); CheckEqual(list1.AddFront(byte1), list1.AddFront(byte1)); list1.Case(Constant(1), (hd, tl) => 2).Unroll(); If(b, list1, list2).Case(Constant(1), (hd, tl) => 2).Unroll(); If(b, h1, h2).GetDstIp().Unroll(); }
private int readPacketRecordData(BinaryReader binaryReader, long len, uint tsSec, long curPacket, bool dontList) { // Begin reading headers long packetStartPos = binaryReader.BaseStream.Position; EthernetHeader ethernetHeader = EthernetHeader.read(binaryReader); // Skip non-IP packets if (ethernetHeader.proto != 8) { binaryReader.BaseStream.Position += len - (binaryReader.BaseStream.Position - packetStartPos); return(1); } IpHeader ipHeader = IpHeader.read(binaryReader); // Skip non-UDP packets if (ipHeader.proto != 17) { binaryReader.BaseStream.Position += len - (binaryReader.BaseStream.Position - packetStartPos); return(1); } UdpHeader udpHeader = UdpHeader.read(binaryReader); bool isSend = (udpHeader.dPort >= 9000 && udpHeader.dPort <= 9013); bool isRecv = (udpHeader.sPort >= 9000 && udpHeader.sPort <= 9013); // Skip non-AC-port packets if (!isSend && !isRecv) { binaryReader.BaseStream.Position += len - (binaryReader.BaseStream.Position - packetStartPos); return(1); } long headersSize = binaryReader.BaseStream.Position - packetStartPos; // Begin reading non-header packet content StringBuilder packetHeadersStr = new StringBuilder(); StringBuilder packetTypeStr = new StringBuilder(); PacketRecord packet = new PacketRecord(); packet.index = records.Count; packet.isSend = isSend; packet.tsSec = tsSec; packet.netPacket = new NetPacket(); packet.data = binaryReader.ReadBytes((int)(len - headersSize)); packet.extraInfo = ""; BinaryReader packetReader = new BinaryReader(new MemoryStream(packet.data)); try { ProtoHeader pHeader = ProtoHeader.read(packetReader); readOptionalHeaders(packet, pHeader.header_, packetHeadersStr, packetReader); if (packetReader.BaseStream.Position == packetReader.BaseStream.Length) { packetTypeStr.Append("<Header Only>"); } uint HAS_FRAGS_MASK = 0x4; // See SharedNet::SplitPacketData if ((pHeader.header_ & HAS_FRAGS_MASK) != 0) { bool first = true; while (packetReader.BaseStream.Position != packetReader.BaseStream.Length) { if (!first) { packetTypeStr.Append(" + "); } readPacket(packet, packetTypeStr, packetReader); first = false; } } if (packetReader.BaseStream.Position != packetReader.BaseStream.Length) { packet.extraInfo = "Didnt read entire packet! " + packet.extraInfo; } } catch (OutOfMemoryException e) { //MessageBox.Show("Out of memory (packet " + curPacket + "), stopping read: " + e); return(2); } catch (Exception e) { packet.extraInfo += "EXCEPTION: " + e.Message + " " + e.StackTrace; } packet.packetHeadersStr = packetHeadersStr.ToString(); packet.packetTypeStr = packetTypeStr.ToString(); records.Add(packet); if (!dontList) { ListViewItem newItem = new ListViewItem(packet.index.ToString()); newItem.SubItems.Add(packet.isSend ? "Send" : "Recv"); newItem.SubItems.Add(packet.tsSec.ToString()); newItem.SubItems.Add(packet.packetHeadersStr); newItem.SubItems.Add(packet.packetTypeStr); newItem.SubItems.Add(packet.data.Length.ToString()); newItem.SubItems.Add(packet.extraInfo); listItems.Add(newItem); } return(0); }