简体   繁体   中英

memcopy uint16_t to char* for UDP transport

I've been working on a UDP reliable transport in C. I have a struct with the following format:

struct  packet
{
  uint16_t cksum; /* Ack and Data */
  uint16_t len;   /* Ack and Data */
  uint32_t ackno; /* Ack and Data */
  uint32_t seqno; /* Data only */
  char data[500]; /* Data only; Not always 500 bytes, can be less */
};
typedef struct packet packet_t;

I then call a function that returns a char* called htonheader(packet_t p). This function is supposed to take all the parts of the header and convert them to network format using the appropriate (htons/htonl) functions.

char* htonheader(packet_t p)
{
  printf("Converting Header to Network Format\n");
  printf("Packet to convert:\n");
  print_pkt(p);

  char *head;               // Converted header to return
  uint16_t u16;             // Used to hold converted values uint16_t
  uint32_t u32;             // Used to hold converted values uint32_t

  u16 = htons(p.cksum);
  printf("u16: %d\n",u16);
  memcpy(head+0,&u16,sizeof(u16));
  printf("Header with Checksum: %s\n",head);

  u16=htons(p.len);
  printf("u16: %d\n",u16);
  memcpy(head+2,&u16,sizeof(u16));
  printf("Header with Length: %s\n",head);

  u32=htonl(p.ackno);
  printf("u32: %d\n",u32);
  memcpy(head+4,&u32,sizeof(u32));
  printf("Header with Ack No: %s\n",head);

  u32=htonl(p.seqno);
  printf("u32: %d\n",u32);
  memcpy(head+8,&u32,sizeof(u32));
  printf("Header with Seq No: %s\n",head);

  return head;
}

Below is the following output when I send a packet with a message:

Converting Header to Network Format
Packet to convert:
Cksum - 0
Len - 13
Ackno - 0
Seqno - 0
Data - test message

u16: 0
Header with Checksum:
u16: 3328
Header with Length:
u32: 0
Header with Ack No:
u32: 0
Header with Seq No:
Generated Header:

If I coded memcpy correctly, it should display a header with some data. Instead it displays nothing, so when I send the header appended with the message, only a message gets sent. Could you guys/girls give me some insight to why its not working? I tried looking at a bunch of similar memcpy examples, even UDP ones, and I still can't find the issue. Thank you.

OK, it's not a string. It's a bunch of integer values that you stuffed into some memory you refer to by a char * .

Second, you need to actually allocate some memory for head to point to.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM