Search code examples
c#socketstcpbytetcpclient

TCP c# Getting specific protocol information from a byte array


When i receive a connection, i get sent a sort of "Connect Request" message with that connection and in that byte array I have 2 Headers and then the data, 1 header that is 16 bytes and one header that is 48 bytes.

But it seems that i am doing something wrong here. I can read the data i receive just fine. But when trying to translate the headers over something seems to be wrong.

I have been giving the documentation that in the first header the lenght of the request is saved in "byte index 2 and with the byte length 2" So byte 2 and 3 from the array. I then know how each bit should function, we know that with Bit 10-15: Each bit will be set to 0. And that Bit 0-9: Contains the actual lenght count.

In my example i receive the data, split it up so i have my 2 headers as their own arrays and try to look at the data, tried to convert the bytes into int for the lenght but that made no sense so i even split up the 2 bytes to try and see but they return data that does not corrospond with what im told. "Byte nr 2 returns 00000000" and "Byte nr 3 returns 00010101"

Heres my code, i hope someone can tell me where ive gone wrong, im certainly getting some data. since i can read the data part of the message without issue.

    public static void StartData(TcpListener listener)
    {
        while (true)
        {
            TcpClient client = listener.AcceptTcpClient();
            Console.WriteLine("Client accepted." + listener.Pending());
            NetworkStream stream = client.GetStream();
            StreamWriter sw = new StreamWriter(client.GetStream());
            byte[] buffer = new byte[client.ReceiveBufferSize];
            int bytesRead = stream.Read(buffer, 0, client.ReceiveBufferSize);
            byte[] header = new byte[16];
            byte[] encHeader = new byte[48];
            for (int i = 0; i < 63; i++)
            {
                if (i <= 15)
                {
                    Console.WriteLine("added to header " + i);
                    header[i] = buffer[i];
                }
                else
                {
                    Console.WriteLine("added to headerEnc " + i);
                    encHeader[i - 15] = buffer[i - 15];
                }   

            }
            Console.WriteLine("Byte nr 2 " + Convert.ToString(header[2], 2).PadLeft(8, '0') + " Byte nr 3 " + Convert.ToString(header[3], 2).PadLeft(8, '0'));
            //Byte nr 2 00000000 Byte nr 3 00010101
            int dataLength = BitConverter.ToInt32(header, 2);
            Console.WriteLine("Data lenght int is " + dataLength);
            //result for datalenght is 790959360

        }
    }

Solution

  • As Jereon van Langen commented, it was indeed because it was big endian