我试图将无符号字符从一个函数返回到另一个函数,但我做不到,因为我是 C 的新手,而且它的数据结构对我来说仍然是个谜。这是调用函数的函数....
void print_ethernet_data(const u_char * Buffer, int Size)
{
unsigned char destination, src;
unsigned short qtype;
get_ethernet_header(Buffer , Size, &destination, &src, &qtype); //The function that is supposed to return the values
printf("|-Dest : %u \n", destination);
printf("|-Protocol : %u \n",qtype);
}
这是函数 get_internet_header
的描述:
void get_ethernet_header(const u_char *Buffer, int Size, unsigned char* destination, unsigned char* src, unsigned short* qtype)
{
struct ether_header *eth = (struct ether_header *)Buffer;
printf( "\n");
printf( "Ethernet Header\n");
printf( " |-Destination Address : %.2X:%.2X:%.2X:%.2X:%.2X:%.2X \n", eth->dhost[0] , eth->dhost[1] , eth->dhost[2] , eth->dhost[3] , eth->dhost[4] , eth->dhost[5] );
printf( " |-Source Address : %.2X:%.2X:%.2X:%.2X:%.2X:%.2X \n", eth->shost[0] , eth->shost[1] , eth->shost[2] , eth->shost[3] , eth->shost[4] , eth->shost[5] );
printf( " |-Protocol : %u \n",(unsigned short)eth->type);
*destination = eth->dhost;
*src = eth->shost;
*qtype = (unsigned short)eth->type;
}
但出于某种我不知道的原因,我无法执行与它为我打印的内容相同的操作。
Ethernet Header
|-Destination Address : 58:49:3B:38:B5:11
|-Source Address : E4:FC:82:FD:32:C1
|-Protocol : 8
|-Dest : 134 //I suppose that this is the address the pointer points to
|-Protocol : 8 //This matches the Protocol printed above
是因为我以错误的方式返回它还是因为我打印数据的格式错误?请注意,协议(protocol)以正确的方式打印,正是我想要的。但目标 mac 没有。
我在 StackOverflow 上阅读了各种答案,但无法使其正常工作。如果有人能帮我解决这个问题,我会很感激。提前致谢。
P.S: 我认为struct ether_header
的描述不是必需的,但如果是,那么我可以稍后编辑它。
EDIT-1:
struct ether_header {
unsigned char dhost[ETHER_ADDR_LEN]; // Destination host address
unsigned char shost[ETHER_ADDR_LEN]; // Source host address
unsigned short type; // IP? ARP? RARP? etc
};
最佳答案
结构的shost
和dhost
成员是数组(或可能是指针)。数组将衰减为指向其第一个元素的指针,即使用普通 eth->dhost
与 ð->dhost[0]
相同。
在现代计算机上,指针通常为 32 或 64 位宽,而 char
通常只有 8 位宽。换句话说,将指针存储在 char
中确实是不可能的。
您需要做的是“返回”指针,而不是单个字节。为此,将 destination
和 src
定义为指针:
unsigned char *destination, *src;
并将函数参数更新为指向指针的指针:
void get_ethernet_header(const u_char *Buffer, int Size,
unsigned char** destination,
unsigned char** src, unsigned short* qtype)
最后记得以正确的方式打印它(就像您在 get_ethernet_header
函数中所做的那样)。其余的可以保持不变。
另一种可能更安全的解决方案是改用数组并复制数据。这样您就不必依赖包含有效结构的“缓冲区”。
关于c - 将多个无符号字符数据从一个函数返回到另一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52925136/