public static string ToString(TzspPacket tzsp) { string result = "Protocol TZSP parser\n"; result += $"Reseived packet length {tzsp.packet.Length} bytes; {BitConverter.ToString(tzsp.packet)}\n"; result += $"\tVersion: {tzsp.header.version};\n"; result += $"\tType: {GetHeaderType(tzsp.header.type)};\n"; result += $"\tEncapsulated protocol: {GetProtocol(tzsp.header.encapsulated_protocol)};\n"; foreach (var item in tzsp.fields) { if (item.Key == "TagPadding" || item.Key == "TagEnd") { result += $"\tField: {item.Key};\n"; } else { var val = typeof(ParserTzsp) .GetMethod($"Get{item.Key}", BindingFlags.Public | BindingFlags.Static) .Invoke(null, new object[] { item.Value }); result += $"\tField: {item.Key}: {val};\n"; } } result += $"\tEncapsulated_packet: {BitConverter.ToString(tzsp.encapsulated_packet)};\n"; result += "\n"; return(result); }
public static TzspPacket Parse(byte[] packet) { var result = new TzspPacket(); var fields = new Dictionary <string, byte []>(); result.fields = fields; if (packet.Length < Marshal.SizeOf(typeof(ProtocolHeader)) + sizeof(byte)) // + TAG_END { throw new Exception(null); } result.header.version = packet[0]; result.header.type = packet[1]; result.header.encapsulated_protocol = BitConverter.ToUInt16(new [] { packet[3], packet[2] }, 0); if (result.header.version != 1 || result.header.type > (int)HeaderType.PortOpener) { throw new Exception(null); } var index = Marshal.SizeOf(typeof(ProtocolHeader)); ParseFields(packet, ref index, ref result.fields); if (packet.Length < index + 1) { throw new Exception(null); } result.encapsulated_packet = new byte[packet.Length - index]; Array.Copy(packet, Convert.ToInt32(index), result.encapsulated_packet, 0, Convert.ToInt32(packet.Length - index)); result.packet = packet; return(result); }