Guy Harris wrote:
> On Thu, Sep 12, 2002 at 01:25:44PM +0200, Ren Hoek wrote:
> 
>>My problem is, that I cannot seem to use a select() on the pcap
>>filedescriptor (pcap_fileno()).  It simply won't return.
> 
> 
> On what OS are you doing this?
>

I'm working on Linux.. I saw that I made a very bad mistake in my program.. I put 
the timeout in front of my loop, instead of inside.. :(

I got it to work.. Here is an example of how it SHOULD be done :) You might want 
to consider putting this example in the libpcap tutorial or FAQ or something :)

Thanks for your reply :)

-- Ren



/* Example code on how to use a select() with libpcap

    Compile with   cc -Wall -o select select.c -lpcap

    By Ren Hoek ([EMAIL PROTECTED])
*/

#include <stdio.h>
#include <sys/time.h>       /* select */
#include <sys/types.h>      /* select */
#include <unistd.h>         /* select, exit */
#include <stdlib.h>         /* atexit */
#include <pcap.h>


void packet_callback(unsigned char *Args,
                      const struct pcap_pkthdr* Pkthdr,
                      unsigned char *Packet)
{
fprintf(stderr, "+"); fflush(stderr);
}


int main(void)
{
int               t;
fd_set            fd_wait;
struct timeval    st;
struct pcap      *pcap;
char              errbuf[PCAP_ERRBUF_SIZE];

char             *device="eth0";       /* Change this to whatever */

pcap = pcap_open_live(device, BUFSIZ, 1, -1, errbuf);

if(pcap == NULL)
   {
   fprintf(stderr, "Could not open device \"%s\": %s\n", device, errbuf);
   exit(1);
   }

if(pcap_setnonblock(pcap, 1, errbuf) == 1)
   {
   fprintf(stderr, "Could not set device \"%s\" to non-blocking: %s\n", device, 
errbuf);
   exit(1);
   }

for(;;)
   {

   /* If you include STDIN_FILENO, be sure to read from it when you get
      traffic from it, or select will return every time it is called,
      since there will still be traffic waiting there.
   */

   FD_ZERO(&fd_wait);
   /*FD_SET(STDIN_FILENO, &fd_wait);*/
   FD_SET(pcap_fileno(pcap), &fd_wait);

   st.tv_sec  = 1;
   st.tv_usec = 0;   /* 1000 = 1 second */

   t=select(FD_SETSIZE, &fd_wait, NULL, NULL, &st);

   switch(t)
     {
     case -1:      /* Something went really wrong */
                   fprintf(stderr, "Argh!\n\n");
                   exit(1);

     case  0:      /* We timed out, no trafffic */
                   fprintf(stderr, ".");
                   break;

     default:      /* We got traffic */
                   pcap_dispatch(pcap, 1, (void *) packet_callback, NULL);
     }

   /* Put your service routine here.. is called when select times out
      or when a packet is processed
   */

   } /* End of for(;;) */

} /* End of main() */

-
This is the TCPDUMP workers list. It is archived at
http://www.tcpdump.org/lists/workers/index.html
To unsubscribe use mailto:[EMAIL PROTECTED]?body=unsubscribe

Reply via email to