从一个函数向另一个函数返回多个无符号字符数据

3

我正在尝试从一个函数返回无符号字符到另一个函数,但是由于我是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

这是因为我返回的方式不正确还是打印数据的格式不正确导致的?请注意,协议以正确的方式打印出来了,这正是我想要的。但是目标mac地址没有打印出来。
我在StackOverflow上阅读了各种答案,但无法使其正常工作。如果有人能帮忙解决这个问题,我将非常感激。提前致谢。
P.S:我认为不需要说明“struct ether_header”的描述,但如果需要,我可以稍后进行编辑。
编辑-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
};

打印dhost或destination的"%s"?对于dhost,它会给出"����2�XI;8�"。而对于destination,则会导致分段错误。 - Devanshu Misra
“附言:我认为不需要ether_header结构的描述,但如果需要的话,我可以稍后进行编辑。” 发布相关定义总是很有用的。 - Jabberwocky
我会立即添加,@Jabberwocky。感谢您指出。 - Devanshu Misra
1个回答

3
结构体中的shostdhost成员是数组(或者可能是指针)。数组会衰减为指向它们第一个元素的指针,也就是说使用普通的eth->dhost&eth->dhost[0]是相同的。
现代计算机上指针通常是32位或64位宽,而char通常只有8位宽。换句话说,在char中存储指针是不可能的。
你需要做的是“返回”指针而不是单个字节。为此,请将destinationsrc定义为指针。
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函数内部一样)。其余内容保持不变。


另一个可能更安全的解决方案是使用数组,然后复制数据。这样就不必依赖于包含结构体的“缓冲区”仍然有效。


shost和dhost是数组,它们的长度被定义为shost[6]和dhost[6]。 - Devanshu Misra
工作得非常完美。感谢您的快速回复。+1 - Devanshu Misra

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接