簡體   English   中英

指向 libpcap 中數據包 len 的指針

[英]pointer to packet len in libpcap

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", dev, errbuf);
        return(2);
    }
    /* Compile and apply the filter */
    if (pcap_compile(handle, &fp, filter_exp, 0, net) == -1) {
        fprintf(stderr, "Couldn't parse filter %s: %s\n", filter_exp, pcap_geterr(handle));
        return(2);
    }
    if (pcap_setfilter(handle, &fp) == -1) {
        fprintf(stderr, "Couldn't install filter %s: %s\n", filter_exp, 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);
    printf("packet len =  [%d]\n", header.len);
}

您會得到相同的答案,事實上,編譯器甚至可能為此生成相同的代碼 (這不是你祖父的 C;C 編譯器比過去做了更多的優化和其他代碼轉換。)

將指向header.len的指針放入一個變量中,然后取消引用該指針,本質上並不是更有效。 例如,如果“加載/推送寄存器指向的內容”比“從寄存器指向的偏移加載/推送”更有效,編譯器很可能會生成代碼來執行此操作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM