blocking pcap and multiple I/O `select `

2019-08-28 04:16发布

问题:

I want to use pcap to capture packets and then send the captured packets to another host my source code snippets are like:

            for(;;){
                    pcap_packet = pcap_next(pcap_handler, &pcap_header);
                    if(pcap_packet !=NULL)
                    printf("capture a packet with length of %d\n", pcap_header.len);

                    // send the packet as payload to the sender, excluding the Ethernet Header
                    n = send(sd_proxy, pcap_packet+ETHERNET_HDR_LEN, pcap_header.len-ETHERNET_HDR_LEN, 0);
                    if(n<0){
                            shutdown(connfd, SHUT_RDWR);
                            close(connfd);
                            break;
                    } new  

            }

so basically, I want program to be blocked by the pcap_next, once a the socket sd_proxy establishes a TCP connection with the other host, if the other host initiate an active TCP close, I want to detect this active close. Ideally, I should use a select and a n=recv(rd_fd, ...) if the other host initiates a active close, select will notice there is something with rd_fd and then I see whether 'n=0' or not. but with pcap, select can't cooperate with pcap

so how to finish my task? thanks!

回答1:

select can't cooperate with pcap

Why not? Have you tried using pcap_get_selectable_fd() on pcap_handler and adding the resulting file descriptor to the file descriptor set in your select() call?

You're working on Linux, so that should Just Work.

(If you were running on a system that uses BPF, such as *BSD or OS X, you might have problems with this, at least with older versions of those OSes; various *BSDs have had their select-with-BPF bugs fixed for a while; on OS X, I fixed it in Lion, so it could have problems on Snow Leopard and earlier.)