Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Text;
- namespace xBot
- {
- /// <summary>
- /// A class designed to hold the packet's data and read throughout it.
- /// </summary>
- public class PacketReader
- {
- private PacketReader() { } // Disable default constructor.
- public PacketReader(byte[] data, bool encrypted)
- {
- packetData = data;
- Pointer = 6; // Skip header.
- Encrypted = encrypted;
- }
- private byte[] packetData { get; set; }
- public bool Encrypted { get; set; }
- public int Pointer { get; set; }
- public ushort Opcode { get { return BitConverter.ToUInt16(packetData, 2); } }
- public int Length { get { return packetData.Length - 6; } }
- public T Read<T>()
- {
- TypeCode type = Type.GetTypeCode(typeof(T));
- int size = System.Runtime.InteropServices.Marshal.SizeOf(typeof(T));
- byte[] tmp = new byte[size]; // Holds the data to be converted.
- Buffer.BlockCopy(packetData, Pointer, tmp, 0, size);
- //Array.Copy(packetData, Pointer, tmp, 0, size);
- object returnValue = null; // The converted value (of the T type)
- switch (type)
- {
- case TypeCode.Byte:
- returnValue = tmp[0];
- break;
- case TypeCode.UInt16:
- returnValue = BitConverter.ToUInt16(tmp, 0);
- break;
- case TypeCode.UInt32:
- returnValue = BitConverter.ToUInt32(tmp, 0);
- break;
- case TypeCode.UInt64:
- returnValue = BitConverter.ToUInt64(tmp, 0);
- break;
- case TypeCode.Single:
- returnValue = BitConverter.ToSingle(tmp, 0);
- break;
- default:
- throw new Exception("Unsupported datatype.");
- }
- Pointer += size;
- return (T)Convert.ChangeType(returnValue, type);
- }
- public byte[] Read(int length)
- {
- byte[] tmp = new byte[length];
- Array.ConstrainedCopy(packetData, Pointer, tmp, 0, length);
- Pointer += length;
- return tmp;
- }
- public string ReadString(Encoding encoding)
- {
- ushort length = Read<ushort>();
- string value = null;
- if (length == 0)
- return "";
- if (encoding == Encoding.Unicode) // Unicode string
- {
- value = encoding.GetString(packetData, Pointer, length * 2);
- Pointer += length * 2;
- }
- else if (encoding == Encoding.ASCII)// ASCII string
- {
- value = encoding.GetString(packetData, Pointer, length);
- Pointer += length;
- }
- return value;
- }
- public void SkipBytes(int amount)
- {
- Pointer += amount;
- }
- public PacketWriter ToPacketWriter()
- {
- int temp = Pointer;
- Pointer = 6;
- PacketWriter writer = new PacketWriter(Opcode, Encrypted);
- writer.AppendArray(Read(Length));
- Pointer = temp;
- return writer;
- }
- }
- }
Add Comment
Please, Sign In to add comment