/// <summary> /// Compute checksum of UDP header. /// </summary> public static ushort SumHeader(UdpHeader udpHeader) { // Do not include existing checksum. int x = udpHeader.srcPort + udpHeader.dstPort + udpHeader.length; return((ushort)((x >> 16) + x)); }
internal void SendCommand(UdpCommandType cmd) { if (CheckCanSend(true) == UdpSendFailReason.None) { UdpStream stream = socket.GetWriteStream(mtu << 3, UdpSocket.HeaderBitSize); stream.WriteByte((byte)cmd, 8); UdpHeader header = MakeHeader(false); header.Pack(stream, socket); UdpHandle handle = MakeHandle(ref header); handle.Object = null; if (SendStream(stream, handle, false)) { // track stats stats.PacketSent((uint)stream.Ptr >> 3); socket.Statistics.PacketSent((uint)stream.Ptr >> 3); } else { // should we do something here????? } } }
// set the checksum field, totalSize covers all the fields for // which the checksum is calculated // offset is points to the beginning of the IP header (!!!) // Should be called after the UDP header + data have been written public static void SetUdpChecksum(byte[] !packet, int ipOffset, ref UdpHeader udpHeader) { // sum IP pseudo ushort ipPayloadSize = 0; ushort headerSum = IPFormat.SumPseudoHeader(packet, ipOffset, ref ipPayloadSize); Debug.Assert(((ushort)udpHeader.length) == ipPayloadSize); // now add it to the udp header + data int ipHeaderSize = (packet[ipOffset] & 0xf) * 4; int udpOffset = ipOffset + ipHeaderSize; Debug.Assert(packet[udpOffset + 6] == 0); Debug.Assert(packet[udpOffset + 7] == 0); ushort payloadSum = IPFormat.SumShortValues(packet, udpOffset, ipPayloadSize); udpHeader.checksum = IPFormat.ComplementAndFixZeroChecksum( IPFormat.SumShortValues(headerSum, payloadSum)); packet[udpOffset + 6] = (byte)(udpHeader.checksum >> 8); packet[udpOffset + 7] = (byte)(udpHeader.checksum & 0xff); }
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); }
public UDPDisplayPacket(IpV4Header ipHeader, UdpHeader udpHeader) { Destination = ipHeader.DestinationAddress; DestinationPort = string.Format("{0} {1}", udpHeader.DestinationPort, UDPPortLookup.GetPortName(udpHeader.DestinationPort)); Source = ipHeader.SourceAddress; SourcePort = string.Format("{0} {1}", udpHeader.SourcePort, UDPPortLookup.GetPortName(udpHeader.SourcePort)); Type = ipHeader.ProtocolType; StringBuilder retVal = new StringBuilder(); if (udpHeader.SourcePort == 520 || udpHeader.DestinationPort == 520) { //RIP Protocol } else if (udpHeader.SourcePort == 161 || udpHeader.DestinationPort == 161 || udpHeader.SourcePort == 162 || udpHeader.DestinationPort == 162 || udpHeader.SourcePort == 10161 || udpHeader.DestinationPort == 10161 || udpHeader.SourcePort == 10162 || udpHeader.DestinationPort == 10162) { //SNMP Protocol } else if (udpHeader.SourcePort == 67 || udpHeader.DestinationPort == 67 || udpHeader.SourcePort == 68 || udpHeader.DestinationPort == 68) { //DHCP Protocol } else if (udpHeader.DestinationPort == 53 || udpHeader.SourcePort == 53) { AppendDNSInfo(udpHeader.Data, retVal); } AppendUDPInfo(udpHeader, retVal); AppendIPInfo(ipHeader, retVal); AppendData(udpHeader.Data, retVal); Data = retVal.ToString(); }
// writes a UDP header to a packet // return the next place to write to // the checksum must be later calculated // (over all the octets of the pseudo header, UDP header and data) public static int WriteUdpHeader(byte[] !buffer, int offset, ref UdpHeader header) { // check we have enough packet space if (buffer.Length - offset < Size) { return(offset); } int o = offset; buffer[o++] = (byte)(((ushort)header.srcPort) >> 8); buffer[o++] = (byte)(((ushort)header.srcPort) & 0xff); buffer[o++] = (byte)(((ushort)header.dstPort) >> 8); buffer[o++] = (byte)(((ushort)header.dstPort) & 0xff); buffer[o++] = (byte)(((ushort)header.length) >> 8); buffer[o++] = (byte)(((ushort)header.length) & 0xff); // checksum buffer[o++] = 0; buffer[o++] = 0; return(o); }
/// <summary> /// ACK报文构造 /// </summary> /// <param name="conv">会话ID</param> /// <param name="sn">msgID</param> /// <param name="cmd">协议</param> /// <param name="headerCode">前后端消息ID</param> public UdpNetMessage(long conv, uint sn, ushort cmd, UdpHeader headerCode) { Conv = conv; SN = sn; Cmd = cmd; HeaderCode = headerCode; }
internal void SendObject(object o) { serializer.SendNext(o); while (serializer.HasQueuedObjects) { UdpSendFailReason reason = CheckCanSend(false); if (reason != UdpSendFailReason.None) { while (serializer.HasQueuedObjects) { socket.Raise(UdpEvent.PUBLIC_OBJECT_SEND_FAILED, this, serializer.NextObject(), reason); } break; } UdpStream stream = socket.GetWriteStream(mtu << 3, UdpSocket.HeaderBitSize); var initialPtr = stream.Ptr; // Erhune: added info object obj = serializer.NextObject(); if (serializer.Pack(stream, ref obj)) { if (stream.Overflowing && (socket.Config.AllowPacketOverflow == false)) { UdpLog.Error("Stream to {0} is overflowing (InitialPtr={1} Ptr={2} Len={3}), not sending {4}", endpoint.ToString(), initialPtr, stream.Ptr, stream.Length, obj); // Erhune: added info socket.Raise(UdpEvent.PUBLIC_OBJECT_SEND_FAILED, this, obj, UdpSendFailReason.StreamOverflow); return; } UdpHeader header = MakeHeader(true); header.Pack(stream, socket, shouldSendClock); UdpHandle handle = MakeHandle(ref header); handle.Object = obj; if (SendStream(stream, handle, alwaysSendMtu)) { // track stats stats.PacketSent((uint)stream.Ptr >> 3); socket.Statistics.PacketSent((uint)stream.Ptr >> 3); // push object to user thread socket.Raise(UdpEvent.PUBLIC_OBJECT_SENT, this, obj); } else { socket.Raise(UdpEvent.PUBLIC_OBJECT_SEND_FAILED, this, obj, UdpSendFailReason.SocketError); } } else { socket.Raise(UdpEvent.PUBLIC_OBJECT_SEND_FAILED, this, obj, UdpSendFailReason.SerializerReturnedFalse); } } }
public static byte[] AddUdpIpHeader(IPEndPoint srcAdr, IPEndPoint dstAdr, byte[] packet) { srcAdr = new IPEndPoint(IPAddress.Parse("25.175.152.176"), 9959); dstAdr = new IPEndPoint(IPAddress.Parse("25.175.152.176"), 9958); byte[] builtPacket = new byte[packet.Length]; ArrayList headerList = new ArrayList(); UdpHeader udpPacket = new UdpHeader(); udpPacket.SourcePort = (ushort)srcAdr.Port; udpPacket.DestinationPort = (ushort)dstAdr.Port; udpPacket.Length = (ushort)(UdpHeader.UdpHeaderLength + packet.Length); udpPacket.Checksum = 0; if (srcAdr.AddressFamily == AddressFamily.InterNetwork) { Ipv4Header ipv4Packet = new Ipv4Header(); ipv4Packet.Version = 4; ipv4Packet.Protocol = (byte)ProtocolType.Udp; ipv4Packet.Ttl = 2; ipv4Packet.Offset = 0; ipv4Packet.Length = (byte)Ipv4Header.Ipv4HeaderLength; ipv4Packet.TotalLength = Convert.ToUInt16(Ipv4Header.Ipv4HeaderLength + UdpHeader.UdpHeaderLength + packet.Length); ipv4Packet.SourceAddress = srcAdr.Address; ipv4Packet.DestinationAddress = dstAdr.Address; udpPacket.Ipv4PacketHeader = ipv4Packet; headerList.Add(ipv4Packet); } else if (srcAdr.AddressFamily == AddressFamily.InterNetworkV6) { Ipv6Header ipv6Packet = new Ipv6Header(); ipv6Packet.Version = 6; ipv6Packet.TrafficClass = 1; ipv6Packet.Flow = 2; ipv6Packet.HopLimit = 2; ipv6Packet.NextHeader = (byte)ProtocolType.Udp; ipv6Packet.PayloadLength = (ushort)(UdpHeader.UdpHeaderLength + packet.Length); ipv6Packet.SourceAddress = srcAdr.Address; ipv6Packet.DestinationAddress = dstAdr.Address; udpPacket.Ipv6PacketHeader = ipv6Packet; headerList.Add(ipv6Packet); } headerList.Add(udpPacket); builtPacket = udpPacket.BuildPacket(headerList, packet); return(builtPacket); }
UdpHandle MakeHandle(ref UdpHeader header) { UdpHandle handle = new UdpHandle(); handle.IsObject = header.IsObject; handle.ObjSequence = header.ObjSequence; handle.SendTime = header.Now; return(handle); }
public static UdpHeader read(BinaryReader binaryReader) { UdpHeader newObj = new UdpHeader(); newObj.sPort = Util.byteSwapped(binaryReader.ReadUInt16()); newObj.dPort = Util.byteSwapped(binaryReader.ReadUInt16()); newObj.len = Util.byteSwapped(binaryReader.ReadUInt16()); newObj.crc = Util.byteSwapped(binaryReader.ReadUInt16()); return(newObj); }
private List<byte> GetPseudoHeaderBytes(UdpHeader udpHeader, uint length) { var currentData = new List<byte>(); currentData.AddRange(udpHeader.PseudoSourcePort.GetBytes()); currentData.AddRange(udpHeader.PseudoDestinationPort1.GetBytes()); currentData.Add(0); currentData.Add(17); currentData.AddRange(GetBytes(length)); return currentData; }
/// <summary> /// 编码默认消息 /// </summary> /// <param name="headerCode">操作码</param> /// <param name="message">二进制业务报文</param> /// <returns>编码成功后的数据</returns> public static UdpNetMessage EncodeMessage(UdpHeader headerCode, byte[] message) { var udpNetMsg = CosmosEntry.ReferencePoolManager.Spawn <UdpNetMessage>(); udpNetMsg.Cmd = UdpProtocol.MSG; udpNetMsg.Len = 0; udpNetMsg.HeaderCode = headerCode; udpNetMsg.ServiceData = message; udpNetMsg.EncodeMessage(); return(udpNetMsg); }
/// <summary> /// /// </summary> /// <param name="udpData"></param> /// <param name="bytesCopied"></param> /// <returns></returns> static public UdpHeader Create(byte[] udpData, ref int bytesCopied) { UdpHeader udpPacketHeader = new UdpHeader(); udpPacketHeader.srcPort = BitConverter.ToUInt16(udpData, 0); udpPacketHeader.destPort = BitConverter.ToUInt16(udpData, 2); udpPacketHeader.udpLength = BitConverter.ToUInt16(udpData, 4); udpPacketHeader.udpChecksum = BitConverter.ToUInt16(udpData, 6); return(udpPacketHeader); }
void AckHandles(UdpHeader header, bool updateRtt) { while (!sendWindow.Empty) { UdpHandle handle = sendWindow.Peek(); int seqDistance = UdpMath.SeqDistance(handle.ObjSequence, header.AckSequence, UdpHeader.SEQ_PADD); if (seqDistance > 0) { break; } if (handle.IsObject) { if (seqDistance <= -UdpSocket.AckRedundancy) { // track stats stats.PacketLost(); socket.Statistics.PacketLost(); // handle lost ObjectLost(handle.Object); } else { if ((header.AckHistory & (1UL << -seqDistance)) != 0UL) { // track stats stats.PacketDelivered(); socket.Statistics.PacketDelivered(); // handle delivered objects ObjectDelivered(handle.Object); } else { // track stats stats.PacketLost(); socket.Statistics.PacketLost(); // handle ObjectLost(handle.Object); } } } if (seqDistance == 0 && header.AckTime > 0) { UpdatePing(recvTime, handle.SendTime, header.AckTime); } sendWindow.Dequeue(); } }
public static bool ReadUdpHeader(IBuffer !buf, out UdpHeader udpHeader) { udpHeader = new UdpHeader(); if (buf.ReadNet16(out udpHeader.srcPort) && buf.ReadNet16(out udpHeader.dstPort) && buf.ReadNet16(out udpHeader.length) && buf.ReadNet16(out udpHeader.checksum)) { return(true); } return(false); }
public override Handler Parse() { var header = new UdpHeader(); header.SourcePort = LoadUInt16ReversingEndian(); header.DestinationPort = LoadUInt16ReversingEndian(); header.Len = LoadUInt16ReversingEndian(); header.Crc = LoadUInt16ReversingEndian(); SetValue(UdpHeaderProperty, header); return GetNextHandler(); //return GetNextHandler(header); }
void FrmMain_Receive(object sender, byte[] e) { byte[] newBytes = new byte[e.Length - 20]; Buffer.BlockCopy(builtPacket, 20, newBytes, 0, newBytes.Length); e = newBytes; int x = 0; var udpHeader = UdpHeader.Create(e, ref x); newBytes = new byte[e.Length - 8]; Buffer.BlockCopy(e, 8, newBytes, 0, newBytes.Length); e = newBytes; if (udpHeader.SourcePort != 9959) { return; } lbTamanho.Invoke(new Action(() => { txtConteudo.Clear(); lbTamanho.Text = e.Length.ToString(); lbCrc.Text = udpHeader.Checksum.ToString(); txtConteudo.Text += "Valor recebido: "; txtConteudo.Text += Encoding.Default.GetString(e, 1, e.Length - 1 - e[0]); txtConteudo.Text += Environment.NewLine; byte ecBytes = e[0]; txtConteudo.Text += "Bytes de correção: " + ecBytes; txtConteudo.Text += Environment.NewLine; int[] realPayloadInt = e.Select(d => (int)d).ToArray(); ReedSolomonDecoder decoder = new ReedSolomonDecoder(GenericGf.QrCodeField256); if (decoder.Decode(realPayloadInt, ecBytes)) { byte[] data = realPayloadInt.Select(d => (byte)d).ToArray(); byte[] message = new byte[data.Length - 1 - ecBytes]; Buffer.BlockCopy(data, 1, message, 0, message.Length); txtConteudo.Text += "Mensagem decodificada: "; txtConteudo.Text += Encoding.Default.GetString(message); } else { txtConteudo.Text += "Não foi possivel recuperar a mensagem original"; } })); }
static MemoryStream GetPayloadAndUpdateHeader(MemoryStream ms, long length, UdpHeader header) { if (length > MAX_PAYLOAD) { throw new ArgumentException("Payload length exceeds 0x4DC maximum"); } byte[] buf = new byte[length]; ms.Read(buf, 0, buf.Length); var payload = new MemoryStream(buf); header.PayloadSize = ( ushort )payload.Length; header.MsgSize = ( uint )payload.Length; return(payload); }
/// <summary> /// MSG报文构造 /// </summary> /// <param name="conv">会话ID</param> /// <param name="sn">msg序号</param> /// <param name="cmd">协议ID</param> /// <param name="headerCode">操作码</param> /// <param name="message">消息内容</param> public UdpNetMessage(long conv, uint sn, byte cmd, UdpHeader headerCode, byte[] message) { if (message == null) { Len = 0; } else { Len = (ushort)message.Length; } Conv = conv; SN = sn; Cmd = cmd; ServiceData = message; HeaderCode = headerCode; }
bool ParseHeader(UdpStream stream) { // we should always start at ptr 0 UdpAssert.Assert(stream.Ptr == 0); UdpHeader header = new UdpHeader(); header.Unpack(stream, socket); // after unpacking the header, the pointer should be at the header size UdpAssert.Assert(stream.Ptr == UdpSocket.HeaderBitSize); int seqDistance = UdpMath.SeqDistance(header.ObjSequence, recvSequence, UdpHeader.SEQ_PADD); // we have to be within window size if (seqDistance > socket.Config.PacketWindow || seqDistance < -socket.Config.PacketWindow) { ConnectionError(UdpConnectionError.SequenceOutOfBounds, string.Format("seqDistance: {0}, socket.Config.PacketWindow: {1}, header.ObjSequence: {2}, recvSequence: {3}", seqDistance, socket.Config.PacketWindow, header.ObjSequence, recvSequence)); return(false); } // this is an old packet if (seqDistance <= 0) { return(false); } // update receive history if (seqDistance >= UdpSocket.AckRedundancy) { recvHistory = 1UL; } else { recvHistory = (recvHistory << seqDistance) | 1UL; } // update our receive stats recvSequence = header.ObjSequence; recvSinceLastSend += 1; // ack sent objects AckHandles(header, true); return(true); }
UdpHeader MakeHeader(bool isObject) { UdpHeader header = new UdpHeader(); header.IsObject = isObject; header.AckHistory = recvHistory; header.AckSequence = recvSequence; header.ObjSequence = UdpMath.SeqNext(sendSequence, UdpHeader.SEQ_MASK); header.Now = socket.GetCurrentTime(); if (recvTime > 0) { header.AckTime = (ushort)UdpMath.Clamp(header.Now - recvTime, 0, socket.Config.MaxPing); } return(header); }
/// <summary> /// Write IP and UDP headers and payload data into a /// byte array. /// </summary> /// <param name="pkt">Array of bytes representing /// packet to be sent.</param> /// <param name="offset">Offset of IP Header within /// packet.</param> /// <param name="ipHeader">IP header to be written /// to packet.</param> /// <param name="udpHeader">UDP header to be written /// to packet.</param> /// <param name="payload">Payload of UDP Packet.</param> /// <param name="payloadOffset">The offset of start /// of the payload data within the payload /// array.</param> /// <param name="payloadLength">The size of the payload data.</param> public static void WriteUdpPacket(byte[] !pkt, int offset, IPFormat.IPHeader !ipHeader, ref UdpHeader udpHeader, byte[] payload, int payloadOffset, int payloadLength) { int udpStart = IPFormat.WriteIPHeader(pkt, offset, ipHeader); int udpEnd = WriteUdpHeader(pkt, udpStart, ref udpHeader); if (pkt != payload || udpEnd != payloadOffset) { Array.Copy(payload, payloadOffset, pkt, udpEnd, payloadLength); } SetUdpChecksum(pkt, offset, ref udpHeader); }
// construct a UDP header from a packet // if something is wrong, return the same start value public static int ReadUdpHeader(byte[] !packet, int udpOffset, out UdpHeader udpHeader) { // initialize an UdpHeader struct udpHeader = new UdpHeader(); udpHeader.srcPort = (ushort)((int)(packet[udpOffset + 0] << 8) | (int)(packet[udpOffset + 1])); udpHeader.dstPort = (ushort)((int)(packet[udpOffset + 2] << 8) | (int)(packet[udpOffset + 3])); udpHeader.length = (ushort)((int)(packet[udpOffset + 4] << 8) | (int)(packet[udpOffset + 5])); udpHeader.checksum = (ushort)((int)(packet[udpOffset + 6] << 8) | (int)(packet[udpOffset + 7]));; return(udpOffset + Size); }
/// <summary> /// Initializes a new instance of the <see cref="UdpPacket"/> class with /// information from the memory stream. /// /// Header is populated from the MemoryStream /// </summary> /// <param name="ms">The stream containing the packet and it's payload data.</param> public UdpPacket(MemoryStream ms) { Header = new UdpHeader(); try { Header.Deserialize(ms); } catch (Exception) { return; } if (this.Header.Magic != UdpHeader.MAGIC) { return; } SetPayload(ms, Header.PayloadSize); }
/// <summary> /// Initializes a new instance of the <see cref="UdpPacket"/> class with /// information from the memory stream. /// /// Header is populated from the MemoryStream /// </summary> /// <param name="ms">The stream containing the packet and it's payload data.</param> public UdpPacket(MemoryStream ms) { Header = new UdpHeader(); try { Header.Deserialize(ms); } catch (Exception) { Payload = new MemoryStream(); return; } if (this.Header.Magic != UdpHeader.MAGIC) { Payload = new MemoryStream(); return; } Payload = GetPayloadAndUpdateHeader(ms, Header.PayloadSize, Header); }
public static bool IsChecksumValid(IPFormat.IPHeader !ipHeader, UdpHeader udpHeader, NetPacket !payload) { // Compute partial checksums of headers ushort checksum = IPFormat.SumPseudoHeader(ipHeader); checksum = IPFormat.SumShortValues(checksum, UdpFormat.SumHeader(udpHeader)); // Checksum payload int length = payload.Available; int end = length & ~1; int i = 0; while (i != end) { int x = ((((int)payload.PeekAvailable(i++)) << 8) + (int)payload.PeekAvailable(i++)); checksum = IPFormat.SumShortValues(checksum, (ushort)x); } if (i != length) { int x = (((int)payload.PeekAvailable(i++)) << 8); checksum = IPFormat.SumShortValues(checksum, (ushort)x); } checksum = IPFormat.ComplementAndFixZeroChecksum(checksum); if (udpHeader.checksum != checksum) { DebugStub.WriteLine("Bad UDP checksum {0:x4} != {1:x4}", __arglist(udpHeader.checksum, checksum)); } return(udpHeader.checksum == checksum); }
public void Execute() { Packet packet; EthernetHeader eth; IPHeader ip; Flow key = new Flow(); FlowStats stats; try { //BinaryReader log = new BinaryReader(new FileStream(@"c:\users\gavin\desktop\20081006.dat", FileMode.Open, FileAccess.Read)); while (!terminated) { try { /*packet = new Packet(); * packet.Time = log.ReadInt64(); * packet.Length = log.ReadInt32(); * packet.Data = log.ReadBytes(log.ReadInt32());*/ packet = pcap.Next(); } catch (Exception e) { packet = null; throw; } if (packet != null) { if (dump != null) { dump.Write(packet.Time); dump.Write(packet.Length); int i = Math.Min(packet.Data.Length, 64); dump.Write(i); dump.Write(packet.Data, 0, i); dump.Flush(); } eth = new EthernetHeader(packet.Data); if (eth.Protocol == (int)EthernetProtocol.IP) { ip = new IPHeader(eth); if (ip.Protocol == IPProtocol.Tcp) { TcpHeader tcp = new TcpHeader(ip); key = new Flow(ip, tcp); stats = tracker.Resolve(key, packet.Time); stats.Last = packet.Time; stats.Packets++; // Bytes at IP, including IP header stats.Bytes += ip.Length; #region debugging /* * // TODO: Verify sorted order of queue - should be right now * FlowStats check = queue.Head; * while (check != null) { * if (check.Next != null) Debug.Assert(check.Last >= check.Next.Last); * check = check.Next; * } */ #endregion } else if (ip.Protocol == IPProtocol.Udp) { try { UdpHeader udp = new UdpHeader(ip); key = new Flow(ip, udp); stats = tracker.Resolve(key, packet.Time); stats.Last = packet.Time; stats.Packets++; // Bytes at IP, including IP header stats.Bytes += ip.Length; } catch (IndexOutOfRangeException e) { using (StreamWriter errorLog = new StreamWriter(Path.Combine(LogFolder, "error.log"), true)) { errorLog.WriteLine(DateTime.Now); errorLog.WriteLine(e.Message); errorLog.WriteLine(e.StackTrace); errorLog.WriteLine(); } if (dump != null) { dump.Write(packet.Time); dump.Write(packet.Length); dump.Write(packet.Data.Length); dump.Write(packet.Data, 0, packet.Data.Length); dump.Flush(); } } catch (Exception ex) { } } else if (ip.Protocol == IPProtocol.Icmp) { // TODO: Deal with ICMP } else if (ip.Protocol == IPProtocol.Gre) { // TODO: Deal with GRE } } else { // TODO: deal with non-IP } #region Age flows /**/ while (tracker.Count > 0 && tracker.Tail.Last < packet.Time - ExpiryInterval) { stats = tracker.Tail; Dump(stats); tracker.Remove(stats); } writer.Flush(); /**/ #endregion } packets++; } } catch (EndOfStreamException e) { // TODO: nothing } catch (Exception e) { //debug.WriteLine("ERROR: " + e.Message); //debug.Flush(); throw e; } }
public static byte[] Construct(IPAddress sourceAddress, ushort sourcePort, IPAddress destinationAddress, ushort destinationPort, byte[] payload) { var bindAddress = IPAddress.Any; // Make sure parameters are consistent //if ((sourceAddress.AddressFamily != destinationAddress.AddressFamily) || (sourceAddress.AddressFamily != bindAddress.AddressFamily)) //{ // throw new Exception("Source and destination address families don't match!"); //} // Start building the headers byte[] builtPacket; UdpHeader udpPacket = new UdpHeader(); ArrayList headerList = new ArrayList(); //Socket rawSocket = null; //SocketOptionLevel socketLevel = SocketOptionLevel.IP; // Fill out the UDP header first Console.WriteLine("Filling out the UDP header..."); udpPacket.SourcePort = sourcePort; udpPacket.DestinationPort = destinationPort; udpPacket.Length = (ushort)(UdpHeader.UdpHeaderLength + payload.Length); udpPacket.Checksum = 0; if (sourceAddress.AddressFamily == AddressFamily.InterNetwork) { Ipv4Header ipv4Packet = new Ipv4Header(); // Build the IPv4 header Console.WriteLine("Building the IPv4 header..."); ipv4Packet.Version = 4; ipv4Packet.Protocol = (byte)ProtocolType.Udp; ipv4Packet.Ttl = 2; ipv4Packet.Offset = 0; ipv4Packet.Length = (byte)Ipv4Header.Ipv4HeaderLength; ipv4Packet.TotalLength = (ushort)System.Convert.ToUInt16(Ipv4Header.Ipv4HeaderLength + UdpHeader.UdpHeaderLength + payload.Length); ipv4Packet.SourceAddress = sourceAddress; ipv4Packet.DestinationAddress = destinationAddress; // Set the IPv4 header in the UDP header since it is required to calculate the // pseudo header checksum Console.WriteLine("Setting the IPv4 header for pseudo header checksum..."); udpPacket.ipv4PacketHeader = ipv4Packet; // Add IPv4 header to list of headers -- headers should be added in th order // they appear in the packet (i.e. IP first then UDP) Console.WriteLine("Adding the IPv4 header to the list of header, encapsulating packet..."); headerList.Add(ipv4Packet); //socketLevel = SocketOptionLevel.IP; } else if (sourceAddress.AddressFamily == AddressFamily.InterNetworkV6) { Ipv6Header ipv6Packet = new Ipv6Header(); // Build the IPv6 header Console.WriteLine("Building the IPv6 header..."); ipv6Packet.Version = 6; ipv6Packet.TrafficClass = 1; ipv6Packet.Flow = 2; ipv6Packet.HopLimit = 2; ipv6Packet.NextHeader = (byte)ProtocolType.Udp; ipv6Packet.PayloadLength = (ushort)(UdpHeader.UdpHeaderLength + payload.Length); ipv6Packet.SourceAddress = sourceAddress; ipv6Packet.DestinationAddress = destinationAddress; // Set the IPv6 header in the UDP header since it is required to calculate the // pseudo header checksum Console.WriteLine("Setting the IPv6 header for pseudo header checksum..."); udpPacket.ipv6PacketHeader = ipv6Packet; // Add the IPv6 header to the list of headers - headers should be added in the order // they appear in the packet (i.e. IP first then UDP) Console.WriteLine("Adding the IPv6 header to the list of header, encapsulating packet..."); headerList.Add(ipv6Packet); //socketLevel = SocketOptionLevel.IPv6; } // Add the UDP header to list of headers after the IP header has been added Console.WriteLine("Adding the UDP header to the list of header, after IP header..."); headerList.Add(udpPacket); // Convert the header classes into the binary on-the-wire representation Console.WriteLine("Converting the header classes into the binary..."); builtPacket = udpPacket.BuildPacket(headerList, payload); /* * // Create the raw socket for this packet * Console.WriteLine("Creating the raw socket using Socket()..."); * rawSocket = new Socket(sourceAddress.AddressFamily, SocketType.Raw, ProtocolType.Udp); * * // Bind the socket to the interface specified * Console.WriteLine("Binding the socket to the specified interface using Bind()..."); * rawSocket.Bind(new IPEndPoint(bindAddress, 0)); * * // Set the HeaderIncluded option since we include the IP header * Console.WriteLine("Setting the HeaderIncluded option for IP header..."); * rawSocket.SetSocketOption(socketLevel, SocketOptionName.HeaderIncluded, 1); * * try * { * // Send the packet! * Console.WriteLine("Sending the packet..."); * int rc = rawSocket.SendTo(builtPacket, new IPEndPoint(destinationAddress, destinationPort)); * Console.WriteLine("send {0} bytes to {1}", rc, destinationAddress.ToString()); * } * catch (SocketException err) * { * Console.WriteLine("Socket error occurred: {0}", err.Message); * // http://msdn.microsoft.com/en-us/library/ms740668.aspx * } * finally * { * // Close the socket * Console.WriteLine("Closing the socket..."); * rawSocket.Close(); * } */ return(builtPacket); }
/// <summary> /// 抓包 /// </summary> /// <param name="s"></param> private void CatchPacket(Object s) { Socket ss = s as Socket;//参数转换 byte[] buffer = new byte[2400];//接收数据的缓冲区 while (true) { if (count > 80000) break; int j = ss.Receive(buffer);//接收数据 if (j > 0)//若接收到数据包 { IPHeader ipheader = new IPHeader(buffer, j); ListViewItem lv = new ListViewItem();//定义一个视图项 count += j;//count用于统计接收的总字节数 lv.Text = ipheader.srcAddr.ToString();//往视图项添加源IP lv.SubItems.Add(ipheader.destAddr.ToString());//往视图项添加目的IP if (ipheader.protocol == 6)//6代表TCP { byte[] tcp = new byte[ipheader.length - ipheader.IPlength]; Array.Copy(buffer, ipheader.IPlength, tcp, 0, j - ipheader.IPlength); TcpHeader tcpHeader = new TcpHeader(tcp, j);//解析TCP报文 lv.SubItems.Add(tcpHeader.sourcePort.ToString()); lv.SubItems.Add(tcpHeader.destinationPort.ToString()); lv.SubItems.Add("TCP"); ListViewItem tcpListView = new ListViewItem(); tcpListView.Text = tcpHeader.sourcePort.ToString(); tcpListView.SubItems.Add(tcpHeader.destinationPort.ToString()); tcpListView.SubItems.Add(tcpHeader.seq.ToString()); tcpListView.SubItems.Add(tcpHeader.ack.ToString()); tcpListView.SubItems.Add(tcpHeader.dataOffset.ToString()); tcpListView.SubItems.Add(tcpHeader.win.ToString()); this.listView2.Items.Add(tcpListView); // if (tcpHeader.destinationPort == 80) // { string str = Encoding.UTF8.GetString(buffer,40,j-40); this.richTextBox1.AppendText("\r\n" + str); // } } else if (ipheader.protocol == 17) {//17代表UDP报文 byte[] udp = new byte[ipheader.length - ipheader.IPlength]; Array.Copy(buffer, ipheader.IPlength, udp, 0, j - ipheader.IPlength); UdpHeader udpHeader = new UdpHeader(udp, j);//解析UDP报文 lv.SubItems.Add(udpHeader.sourcePort.ToString()); lv.SubItems.Add(udpHeader.destinationPort.ToString()); lv.SubItems.Add("UDP"); } else {//其他协议 lv.SubItems.Add(" "); lv.SubItems.Add(" "); lv.SubItems.Add("Others"); } lv.SubItems.Add((ipheader.length).ToString()); lv.SubItems.Add(count.ToString()); this.listView1.Items.Add(lv); } } }
/// <summary> /// /// </summary> /// <param name="udpData"></param> /// <param name="bytesCopied"></param> /// <returns></returns> public static UdpHeader Create(byte[] udpData, ref int bytesCopied) { UdpHeader udpPacketHeader = new UdpHeader(); udpPacketHeader.srcPort = BitConverter.ToUInt16(udpData, 0); udpPacketHeader.destPort = BitConverter.ToUInt16(udpData, 2); udpPacketHeader.udpLength = BitConverter.ToUInt16(udpData, 4); udpPacketHeader.udpChecksum = BitConverter.ToUInt16(udpData, 6); return udpPacketHeader; }
public void Assign(IPHeader ip, UdpHeader udp) { Source = new IPEndPoint(ip.SourceIp, udp.SourcePort); Destination = new IPEndPoint(ip.DestinationIp, udp.DestinationPort); Protocol = ip.Protocol; }
public Flow(IPHeader ip, UdpHeader udp) { Assign(ip, udp); }
/// <summary> /// 抓包 /// </summary> /// <param name="s"></param> private void CatchPacket(Object s) { Socket ss = s as Socket; //参数转换 byte[] buffer = new byte[2400]; //接收数据的缓冲区 while (true) { if (count > 80000) { break; } int j = ss.Receive(buffer); //接收数据 if (j > 0) //若接收到数据包 { IPHeader ipheader = new IPHeader(buffer, j); ListViewItem lv = new ListViewItem(); //定义一个视图项 count += j; //count用于统计接收的总字节数 lv.Text = ipheader.srcAddr.ToString(); //往视图项添加源IP lv.SubItems.Add(ipheader.destAddr.ToString()); //往视图项添加目的IP if (ipheader.protocol == 6) //6代表TCP { byte[] tcp = new byte[ipheader.length - ipheader.IPlength]; Array.Copy(buffer, ipheader.IPlength, tcp, 0, j - ipheader.IPlength); TcpHeader tcpHeader = new TcpHeader(tcp, j); //解析TCP报文 lv.SubItems.Add(tcpHeader.sourcePort.ToString()); lv.SubItems.Add(tcpHeader.destinationPort.ToString()); lv.SubItems.Add("TCP"); ListViewItem tcpListView = new ListViewItem(); tcpListView.Text = tcpHeader.sourcePort.ToString(); tcpListView.SubItems.Add(tcpHeader.destinationPort.ToString()); tcpListView.SubItems.Add(tcpHeader.seq.ToString()); tcpListView.SubItems.Add(tcpHeader.ack.ToString()); tcpListView.SubItems.Add(tcpHeader.dataOffset.ToString()); tcpListView.SubItems.Add(tcpHeader.win.ToString()); this.listView2.Items.Add(tcpListView); // if (tcpHeader.destinationPort == 80) // { string str = Encoding.UTF8.GetString(buffer, 40, j - 40); this.richTextBox1.AppendText("\r\n" + str); // } } else if (ipheader.protocol == 17) {//17代表UDP报文 byte[] udp = new byte[ipheader.length - ipheader.IPlength]; Array.Copy(buffer, ipheader.IPlength, udp, 0, j - ipheader.IPlength); UdpHeader udpHeader = new UdpHeader(udp, j); //解析UDP报文 lv.SubItems.Add(udpHeader.sourcePort.ToString()); lv.SubItems.Add(udpHeader.destinationPort.ToString()); lv.SubItems.Add("UDP"); } else {//其他协议 lv.SubItems.Add(" "); lv.SubItems.Add(" "); lv.SubItems.Add("Others"); } lv.SubItems.Add((ipheader.length).ToString()); lv.SubItems.Add(count.ToString()); this.listView1.Items.Add(lv); } } }
UdpHandle MakeHandle(ref UdpHeader header) { UdpHandle handle = new UdpHandle(); handle.IsObject = header.IsObject; handle.ObjSequence = header.ObjSequence; handle.SendTime = header.Now; return handle; }
UdpHeader MakeHeader(bool isObject) { UdpHeader header = new UdpHeader(); header.IsObject = isObject; header.AckHistory = recvHistory; header.AckSequence = recvSequence; header.ObjSequence = UdpMath.SeqNext(sendSequence, UdpHeader.SEQ_MASK); header.Now = socket.GetCurrentTime(); if (recvTime > 0) { header.AckTime = (ushort) UdpMath.Clamp(header.Now - recvTime, 0, socket.Config.MaxPing); } return header; }
bool ParseHeader(UdpStream stream) { // we should always start at ptr 0 UdpAssert.Assert(stream.Ptr == 0); UdpHeader header = new UdpHeader(); header.Unpack(stream, socket); // after unpacking the header, the pointer should be at the header size UdpAssert.Assert(stream.Ptr == UdpSocket.HeaderBitSize); int seqDistance = UdpMath.SeqDistance(header.ObjSequence, recvSequence, UdpHeader.SEQ_PADD); // we have to be within window size if (seqDistance > socket.Config.PacketWindow || seqDistance < -socket.Config.PacketWindow) { ConnectionError(UdpConnectionError.SequenceOutOfBounds, string.Format("seqDistance: {0}, socket.Config.PacketWindow: {1}, header.ObjSequence: {2}, recvSequence: {3}", seqDistance, socket.Config.PacketWindow, header.ObjSequence, recvSequence)); return false; } // this is an old packet if (seqDistance <= 0) return false; // update receive history if (seqDistance >= UdpSocket.AckRedundancy) { recvHistory = 1UL; } else { recvHistory = (recvHistory << seqDistance) | 1UL; } // update our receive stats recvSequence = header.ObjSequence; recvSinceLastSend += 1; // ack sent objects AckHandles(header, true); return true; }