Here's the issue, I'm building a payload of TLVs to send onto the network. I need to pass multiple structs of the same type into a single header struct. With the below code I can pass one occurence of the tlv struct into the pHeader struct but then when I go to copy additional tlv structs I think I'm just overwriting memory. How do I append additional tlv structs at the end of the previous tlv struct?
To be simple, how to I memcpy to the end of the previous memcpy?
Code:
int main(int argc, char *argv[]) {
struct packet
{
u_int8_t version;
u_int8_t length;
char val[10];
u_int8_t *data;
};
struct packet *pHeader;
pHeader = malloc(sizeof(struct packet) + MAX_PACKET_BUFFER_SIZE);
pHeader->version = 0x7;
strcpy(pHeader->val,"foobar");
struct tlvs
{
u_int8_t type;
u_int8_t len;
char value[MAX_TLV_VALUE];
};
struct tlvs *tlv;
tlv = malloc(sizeof(struct tlvs));
int temp = 0;
int valueSize = 0;
int i;
if (argc < 2)
printf("Usage: foobar\n");
else
for(i=1; i < argc ;i++)
{
switch(argv[i][1])
{
case 's':
if (i+1 >= argc)
printf("Usage: foobar\n");
valueSize = strlen(argv[i]);
strcpy(tlv->value,argv[++i]);
tlv->type = sAttrib;
tlv->len = valueSize + 2;
temp += valueSize;
break;
case 'h':
if (i+1 >= argc)
printf("Usage: foobar\n");
valueSize = strlen(argv[i]);
strcpy(tlv->value,argv[++i]);
tlv->type = hAttrib;
tlv->len = valueSize + 2;
temp += valueSize;
break;
case 'f':
if (i+1 >= argc)
printf("Usage: foobar\n");
valueSize = strlen(argv[i]);
strcpy(tlv->value,argv[++i]);
tlv->type = fAttrib;
tlv->len = valueSize + 2;
temp += valueSize;
break;
default:
printf("Usage: foobar\n");
break;
}
}
/* Building header */
memcpy(&pHeader->data, tlv, sizeof(struct tlvs));
int pHeader_s = (sizeof(struct packet) + temp);
pHeader->length = pHeader_s;
u_char *payload = malloc(pHeader_s);
memset(&payload,0,sizeof(payload));
memcpy(&payload,&pHeader,pHeader_s);
/* send (u_char*)payload onto network */
Please let me know if you need more information.
Thanks!