在下面的代码中,有人可以解释一下
以下是完整代码链接:发送以太网帧
struct ether_header *eh = (struct ether_header *) sendbuf;
这行发生了什么吗?我理解它创建了一个指针eh
,类型为ether_header
,在右手边,你将sendbuf
强制转换为struct ether_header
的指针。但是如果sendbuf
是一个char array
,你怎么能做到这一点呢?另外为什么要这样做?以下是完整代码链接:发送以太网帧
#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;
char []
应该算是字符串的一种形式... 但是没错,这是个笔误;应该是“strict aliasing”。 - Christian Gibbonsstruct ether_header *eh = (struct ether_header *) sendbuf;
是未定义行为。避免使用这种编码风格。 - chux - Reinstate Monica