我一直以为在一个程序只能打开一次设备, 看样子是可以打开多次的。 #include <pcap.h> #include <stdio.h> int main(int argc, char *argv[]) { pcap_t *h1, *h2; /* Session handle */ char *dev; /* The device to sniff on */ char errbuf[PCAP_ERRBUF_SIZE]; /* Error string */ struct bpf_program fp; /* The compiled filter */ char *exp1 = "port 22"; char *exp2 = "port 80"; bpf_u_int32 mask; /* Compile and apply the filter */ bpf_u_int32 net; /* Our IP */ struct pcap_pkthdr header; /* The header that pcap gives us */ const u_char *packet; /* The actual packet */ 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; } printf("net = %u, masx = %u/n", net, mask); h1 = pcap_open_live(dev, BUFSIZ, 1, 1000, errbuf); if (h1 == NULL) { fprintf(stderr, "Couldn't open device %s -- %s/n", dev, errbuf); return 2; } h2 = pcap_open_live(dev, BUFSIZ, 1, 1000, errbuf); if (h2 == NULL) { fprintf(stderr, "Couldn't open device %s -- %s/n", dev, errbuf); return 2; } if (pcap_compile(h1, &fp, exp1, 0, net) == -1) { fprintf(stderr, "Couldn't parse filter %s: %s/n", exp1, pcap_geterr(h1)); return 2; } if (pcap_setfilter(h1, &fp) == -1) { fprintf(stderr, "Couldn't install filter %s: %s/n", exp1, pcap_geterr(h1)); return 2; } if (pcap_compile(h2, &fp, exp2, 0, net) == -1) { fprintf(stderr, "Couldn't parse filter %s: %s/n", exp2, pcap_geterr(h2)); return 2; } if (pcap_setfilter(h2, &fp) == -1) { fprintf(stderr, "Couldn't install filter %s: %s/n", exp2, pcap_geterr(h2)); return 2; } /* Grab a packet */ packet = pcap_next(h1, &header); printf("Jacked a packet with length of [%d] from port 22/n", header.len); packet = pcap_next(h2, &header); printf("Jacked a packet with length of [%d] from port 80/n", header.len); /* And close the session */ pcap_close(h1); pcap_close(h2); return 0; }