diff options
Diffstat (limited to 'src/peer_protocol.zig')
-rw-r--r-- | src/peer_protocol.zig | 26 |
1 files changed, 26 insertions, 0 deletions
diff --git a/src/peer_protocol.zig b/src/peer_protocol.zig new file mode 100644 index 0000000..cd70ad2 --- /dev/null +++ b/src/peer_protocol.zig @@ -0,0 +1,26 @@ +const std = @import("std"); + +pub const Handshake = struct { + info_hash: [20]u8, + peer_id: [20]u8, + + pub fn read(reader: anytype) !Handshake { + var msg = [_]u8{0} ** 68; + try reader.readNoEof(&msg); + if (msg[0] != 19) return error.ProtocolError; + if (!std.mem.eql(u8, msg[1..20], "BitTorrent protocol")) return error.ProtocolError; + //if (!std.mem.allEqual(u8, msg[20..28], 0)) return error.ProtocolError; + var res: Handshake = undefined; + @memcpy(&res.info_hash, msg[28..48]); + @memcpy(&res.peer_id, msg[48..68]); + return res; + } + + pub fn write(self: Handshake, writer: anytype) !void { + try writer.writeByte(19); + try writer.writeAll("BitTorrent protocol"); + try writer.writeByteNTimes(0, 8); + try writer.writeAll(&self.info_hash); + try writer.writeAll(&self.peer_id); + } +}; |