在下面的代码中,有人可以解释 struct ether_header *eh = (struct ether_header *) sendbuf;
线上发生了什么吗? ?我知道它正在创建一个指针 eh
类型 ether_header
在 RHS 上您正在转换 sendbuf
成为tyoe的指针struct ether_header
。但你怎么能做到这一点是sendbuf
是 char array
?还有你为什么要这样做?
这里是完整代码的链接send ethernet frame
#include <arpa/inet.h>
#include <linux/if_packet.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <net/if.h>
#include <netinet/ether.h>
int main(int argc, char *argv[])
{
int sockfd;
struct ifreq if_idx;
struct ifreq if_mac;
int tx_len = 0;
char sendbuf[BUF_SIZ];
struct ether_header *eh = (struct ether_header *) sendbuf;
最佳答案
But how can you do this
isifsendbuf
is achar
array?
代码不应该这样做。
将指针强制转换为最初不是该类型的有效指针的类型是未定义行为 (UB)。
char sendbuf[BUF_SIZ];
struct ether_header *eh = (struct ether_header *) sendbuf; // UB
至少,考虑struct ether_header
是否有偶数地址的对齐要求,而sendbuf[]
是否从奇数地址开始。该分配可能会终止程序。
第二个问题是未发布的代码稍后可能会使用 sendbuf[]
和 eh
执行操作,这可能违反严格的别名规则 @Andrew Henle .
更好的方法是使用 union
。现在成员已对齐,union
处理严格的别名规则。
union {
char sendbuf[BUF_SIZ];
struct ether_header eh;
} u;
<小时/>
Also why would you do this?
允许从 2 个数据类型角度访问数据。也许是为了对 u
进行数据转储。
关于将 char 数组转换为 struct * 类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48099028/