简体   繁体   English

将uint16_t复制到char *以进行UDP传输

[英]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: 我一直在用C进行UDP可靠传输。我有一个结构,格式如下:

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). 然后,我调用一个函数,该函数返回一个名为htonheader(packet_t p)的char *。 This function is supposed to take all the parts of the header and convert them to network format using the appropriate (htons/htonl) functions. 该函数应该采用头文件的所有部分,并使用适当的(htons / htonl)函数将其转换为网络格式。

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. 如果我正确编码了memcpy,它应该显示带有一些数据的标头。 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. 我尝试查看许多类似的memcpy示例,甚至是UDP实例,但仍然找不到问题。 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 * . 这是一堆整数值,您将它们填充到char *引用的某些内存中。

Second, you need to actually allocate some memory for head to point to. 其次,你需要实际分配的一些内存head ,以点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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