Beispiel #1
0
        public bool Handshake(byte[] hash, byte[] peerId)
        {
            if (hash == null)
            {
                throw new ArgumentNullException(nameof(hash), "Hash cannot be null");
            }
            if (peerId == null)
            {
                throw new ArgumentNullException(nameof(peerId), "Peer ID cannot be null");
            }

            if (hash.Length != 20)
            {
                throw new ArgumentOutOfRangeException(nameof(hash), "hash must be 20 bytes exactly");
            }
            if (peerId.Length != 20)
            {
                throw new ArgumentOutOfRangeException(nameof(peerId), "Peer ID must be 20 bytes exactly");
            }

            byte[] reservedBytes = { 0, 0, 0, 0, 0, 0, 0, 0 };

            foreach (var extension in _btProtocolExtensions)
            {
                for (var x = 0; x < 8; x++)
                {
                    reservedBytes[x] |= extension.ByteMask[x];
                }
            }

            var sendBuf = (new[] { (byte)_bitTorrentProtocolHeader.Length }).Cat(_bitTorrentProtocolHeader).Cat(reservedBytes).Cat(hash).Cat(peerId);

            try
            {
                var len = Socket.Send(sendBuf);
                if (len != sendBuf.Length)
                {
                    throw new Exception("Didnt sent entire handshake");
                }
            }
            catch (SocketException ex)
            {
                Trace.TraceInformation(ex.Message);
                return(false);
            }

            foreach (IProtocolExtension extension in _btProtocolExtensions)
            {
                extension.OnHandshake(this);
            }

            _handshakeSent = true;

            return(true);
        }