someone someone - 3 months ago 13
C Question

how do i build a protocol header and body over a tcp socket in c

im writing a tacacs+ client,

im trying to write a simple packet to send to the server,
i checked the rfc(here:https://tools.ietf.org/html/draft-grant-tacacs-02) page and i saw the protocol needs to get this header in every packet:

+----------------+----------------+----------------+----------------+
|major | minor | | | |
|version| version| type | seq_no | flags |
+----------------+----------------+----------------+----------------+
| |
| session_id |
+----------------+----------------+----------------+----------------+
| |
| length |
+----------------+----------------+----------------+----------------+


now im pretty new with this,
and im not sure how do i build this header,
is creating a buffer like this good enough?:

snprintf(buffer, sizeof(buffer), "%x%x%x%x%x",version,version,type,seq,flags,session_id,length);


and then take this buffer and attach it the body in the same way and send:

send(socket,buffer,sizeof(buffer),0);


or is there another way of doing this whole packet building?

thanks ahead.

Answer

What you have doesn't produce the right output at all!

The following is portable:

#include <stdint.h>
#include <stdlib.h>

uint8_t* pack_uint8(uint8_t* dest, uint8_t src) {
   *(dest++) = src;
   return dest;
}

uint8_t* pack_uint32be(uint8_t* dest, uint32_t src) {
   *(dest++) = src >> 24;
   *(dest++) = (src >> 16) & 0xFF;
   *(dest++) = (src >> 8) & 0xFF;
   *(dest++) = src & 0xFF;
   return dest;
}

uint8_t* build_header(
   uint8_t maj_version,
   uint8_t min_version,
   uint8_t type,
   uint8_t seq,
   uint8_t flags,
   uint32_t session_id,
   uint32_t length
) {
   uint8_t* buf = malloc(12);
   uint8_t* p = buf;
   p = pack_uint8(p, ( maj_version << 4 ) | min_version);
   p = pack_uint8(p, type);
   p = pack_uint8(p, seq);
   p = pack_uint8(p, flags);
   p = pack_uint32be(p, session_id);
   p = pack_uint32be(p, length);
   return buf;
}