0

I am trying to create a sniffer which reads a text being sent from server to client using inet address 127.0.0.1 (loopback address). Program keeps stays halts even when client has received data from server.

CODE of sniffer :

int main(int argc,char **argv)
{ 
    char *dev; 
    char errbuf[PCAP_ERRBUF_SIZE];
    pcap_t* descr;
    bpf_u_int32 maskp;          /* subnet mask               */
    bpf_u_int32 netp;           /* ip*/
    struct bpf_program fp;      /* hold compiled program            */
    char *filter = "host 127.0.0.1";
    //char *filter = "port 5000";

    dev = pcap_lookupdev(errbuf);
    if(dev == NULL)
    { printf("%s\n",errbuf); exit(1); }
                printf("call success");

    /* ask pcap for the network address and mask of the device */
    pcap_lookupnet(dev,&netp,&maskp,errbuf);

    descr = pcap_open_live(dev,BUFSIZ,1,-1,errbuf);
    if(descr == NULL)
    { printf("pcap_open_live(): %s\n",errbuf); exit(1); }

                    /* Lets try and compile the program.. non-optimized */
    if(pcap_compile(descr,&fp,filter,0,netp) == -1)
    { fprintf(stderr,"Error calling pcap_compile\n"); exit(1); }

    /* set the compiled program as the filter */
    if(pcap_setfilter(descr,&fp) == -1)
    { fprintf(stderr,"Error setting filter\n"); exit(1); }


    pcap_loop(descr,2,callback,NULL);

    fprintf(stdout,"\nfinished\n");
    return 0;
}
Usman
  • 3
  • 1

1 Answers1

0

You're passing -1 as the to_ms argument to pcap_open_live(). The behavior for a negative timeout is undefined; you should specify a positive value. The value is in units of milliseconds; tcpdump uses 1000, i.e. 1 second, whereas Wireshark uses 250, i.e. 1/4 second.

You're also capturing on the default device, as you're using pcap_lookupdev(). That is rarely, if ever, the loopback device, so if you capture on the default device, you will rarely, if ever, see any traffic if you use the filter host 127.0.0.1. If the server and client are both running on the same machine as the machine on which you're running your program, you need to capture on the loopback device, which is named "lo" on Linux. If the server and client are not both running on the same machine, then your traffic will not use address 127.0.0.1, and you will need to pick a different address.