首页 > 解决方案 > 如何在发送数据包时避免填充

问题描述

我想使用 write systemcall 发送一个数据包。我创建了数据包,它的大小是 46 字节。当我在wireshark的程序中发送数据包时,长度为60字节,14字节为填充。如何在没有填充的情况下发送数据包。

我不能使用套接字命令。

struct x {
 bool is_active;
 bool is_owner;
 int fd1;
 int fd2;
 char pkt_hdr[sizeof(struct ether_header) + sizeof(struct ip)];
 struct interface *ifp;
 int fd_bufflen;
 struct ipaddr src;
 uint8_t ibuf[IP_MAXPACKET];
 int family;
 struct vrrp_vrouter *vr;
 struct list *addrs;
 bool ad;
 bool ga;
 bool nd;
 uint8_t priority;
 uint16_t ma_val;
 uint16_t sk_tm;
 uint16_t ma_val;
 struct ethaddr vmac;
  struct {
    int state;
  } fsm;

  struct {
    uint32_t ad_cnt;
    uint32_t ar_cnt;
    uint32_t g_cnt;
    uint32_t un_cnt;
    uint32_t t_cnt;
  } stats;

  struct thread *t_ti;
  struct thread *t_adti;
  struct thread *t_read;
  struct thread *t_write;
};
.
.
.
size_t buf_len = pktsz + sizeof r->pkt_hdr;
. 
.
.

/* Ethernet Header */
struct ether_header *ether_hdr = (struct ether_header *)buf;
.
.
.

/* IP Header */

struct ip *ip_hdr = (struct ip *) (ether_hdr + 1);
ip_hdr->ip_len = htons(buf_len - sizeof(struct ether_header));
ip_hdr->ip_src = r->src.ipaddr_v4;
ip_hdr->ip_sum = in_cksum(ip_hdr, sizeof(struct ip));

/* Payload */
memcpy((void *)(buf + sizeof r->pkt_hdr), (const void *)pkt, pktsz);

ssize_t sent = write(fd, buf, buf_len);
free(buf);

buf_len 是:46

pktsz : 12

r->pkt_hdr 大小:34

长度为 46。

标签: c

解决方案


打包可防止编译器在 GCC 下使用__attribute__((__packed__))进行填充——这必须明确请求。

有关更多说明,请通过以下链接: https ://www.geeksforgeeks.org/structure-member-alignment-padding-and-data-packing/


推荐阅读