指向libpcap中的数据包len的指针

问题描述

libpcap中,我有这段代码用于嗅探和打印数据包长度

int main(int argc,char *argv[])
 {
    pcap_t *handle;         /* Session handle */
    char *dev;          /* The device to sniff on */
    char errbuf[PCAP_ERRBUF_SIZE];  /* Error string */
    struct bpf_program fp;      /* The compiled filter */
    char filter_exp[] = "port 23";  /* The filter expression */
    bpf_u_int32 mask;       /* Our netmask */
    bpf_u_int32 net;        /* Our IP */
    struct pcap_pkthdr header;  /* The header that pcap gives us */
    const u_char *packet;       /* The actual packet */

    /* Define the device */
    dev = pcap_lookupdev(errbuf);
    if (dev == NULL) {
        fprintf(stderr,"Couldn't find default device: %s\n",errbuf);
        return(2);
    }
    /* Find the properties for the device */
    if (pcap_lookupnet(dev,&net,&mask,errbuf) == -1) {
        fprintf(stderr,"Couldn't get netmask for device %s: %s\n",dev,errbuf);
        net = 0;
        mask = 0;
    }
    
    /* Open the session in promiscuous mode */
    handle = pcap_open_live(dev,BUFSIZ,1,1000,errbuf);
    if (handle == NULL) {
        fprintf(stderr,"Couldn't open device %s: %s\n",errbuf);
        return(2);
    }
    /* Compile and apply the filter */
    if (pcap_compile(handle,&fp,filter_exp,net) == -1) {
        fprintf(stderr,"Couldn't parse filter %s: %s\n",pcap_geterr(handle));
        return(2);
    }
    if (pcap_setfilter(handle,&fp) == -1) {
        fprintf(stderr,"Couldn't install filter %s: %s\n",pcap_geterr(handle));
        return(2);
    }
    while(1)
    {
        packet = pcap_next(handle,&header);
        printf("packet len =  [%d]\n",header.len);
    }
    pcap_close(handle);
    return(0);
 }

我想在循环之前将指针设置为header.len并在每次迭代时打印它:

bpf_u_int32 * len= &header.len
while(1)
{
    packet = pcap_next(handle,&header);
    printf("packet len =  [%d]\n",*len);
}

这有效吗,或者header.len的地址在每次迭代中都可以更改?

解决方法

header的地址在该循环中不会更改。

但是,没有理由这样做

bpf_u_int32 * len= &header.len
while(1)
{
    packet = pcap_next(handle,&header);
    printf("packet len =  [%d]\n",*len);
}

不只是

while(1)
{
    packet = pcap_next(handle,header.len);
}

您将得到相同的答案,实际上,编译器甚至可能为此生成相同的 code 。 (这不是您祖父的C语言; C编译器比过去进行了更多的优化和其他代码转换。)

将指向header.len的指针放入变量中,然后取消对该指针的引用,本质上并没有更高的效率。如果 例如,“加载/推动寄存器指向的内容”比“从寄存器指向的偏移量加载/推动”更有效,则编译器可能会生成代码来执行此操作。