int pcap_fileno(pcap_t *handle); pcap_fileno返回pcap的文件描述符, 这样我们就可以使用select函数。 #include <sys/select.h> #include <sys/types.h> #include <unistd.h> #include <pcap.h> #include <stdio.h> int main(int argc, char *argv[]) { pcap_t *h1, *h2; /* Session handle */ int fd1, fd2; 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 */ fd_set rfs; 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; } fd1 = pcap_fileno(h1); fd2 = pcap_fileno(h2); printf("fd1 = %d, fd2 = %d/n", fd1, fd2); FD_ZERO(&rfs); FD_SET(fd1, &rfs); FD_SET(fd2, &rfs); while (select(5, &rfs, 0, 0, 0) != -1) { if (FD_ISSET(pcap_fileno(h1), &rfs)) { packet = pcap_next(h1, &header); printf("Jacked a packet with length of [%d] from port 22/n", header.len); } if (FD_ISSET(pcap_fileno(h2), &rfs)) { packet = pcap_next(h2, &header); printf("Jacked a packet with length of [%d] from port 80/n", header.len); } FD_ZERO(&rfs); FD_SET(fd1, &rfs); FD_SET(fd2, &rfs); } perror("select:"); /* And close the session */ pcap_close(h1); pcap_close(h2); return 0; }