public void SetChecksum(ref byte[] packet) { RPH rph = RPH.Deserialize(packet); var md5 = MD5.Create(); rph._checksum = BitConverter.ToInt32(md5.ComputeHash(packet), 0); byte[] newHead = rph.Serialize(); Array.Copy(newHead, packet, newHead.Length); }
public bool IsCorrupt(byte[] packet) { var copyPacket = new byte[packet.Length]; Array.Copy(packet, copyPacket, packet.Length); var recvRph = RPH.Deserialize(packet); int recvChecksum = recvRph._checksum; recvRph._checksum = 0; byte[] newHead = recvRph.Serialize(); Array.Copy(newHead, copyPacket, newHead.Length); var md5 = MD5.Create(); int calcChecksum = BitConverter.ToInt32(md5.ComputeHash(copyPacket), 0); return(calcChecksum != recvChecksum); }
public bool Init() { _acknowledgedBytes = 0; _fileEnding = ""; _fileRecv = false; NrPackets = 0; DisplayServerInformation(); Console.WriteLine("Warte auf Verbindung von Clienten..."); _sender = new IPEndPoint(IPAddress.Any, 0); IPEndPoint endAddress = new IPEndPoint(IPAddress.Any, ListenPort); try { if (_udpClient == null) { _udpClient = new UdpClient(endAddress); } byte[] dgram = _udpClient.Receive(ref _sender); RPH rph = RPH.Deserialize(dgram); if (IsCorrupt(rph)) { // send nak return(false); } else { _currentState = State.SendSynAck; } _fileEnding = rph._fileEnding; _payloadBuffer = new byte[rph._fileSize]; return(true); } catch (SocketException e) { Console.WriteLine(e); return(false); } }
public void AckPacket(byte[] buf) { // Deserialize our protocol var rph = RPH.Deserialize(buf); // Calculate the size of our protocol int headSize = rph.GetByteLength(); // if received packet is a retransmission or corrupt or packet reordering took place if (IsCorrupt(buf) || _acknowledgedBytes != rph._seqNr) { // Send NAck Console.WriteLine("Packet was corrupt or it was a retransmission"); var ack = RPH.CreateNAckPacket(); var dgram = ack.Serialize(); SetChecksum(ref dgram); _udpClient.Send(dgram, dgram.Length, _sender); } else if (!IsCorrupt(buf) && rph._seqNr == _acknowledgedBytes) { _acknowledgedBytes = rph._seqNr + buf.Length - headSize; // Copy received bytes into receive buffer Array.Copy(buf, headSize, _payloadBuffer, rph._seqNr, buf.Length - headSize); var ack = RPH.CreateAckPacket(_acknowledgedBytes, 0); var dgram = ack.Serialize(); SetChecksum(ref dgram); _udpClient.Send(dgram, dgram.Length, _sender); if (_payloadBuffer.Length == _acknowledgedBytes) { _currentState = State.SaveToFile; } } else { Console.WriteLine("Not defined"); } NrPackets++; // Console.WriteLine(NrPackets + ".Paket"); // Console.WriteLine("Sequenznummer: " + rph._seqNr); // Console.WriteLine("AckNr: " + _acknowledgedBytes); }