listening using Pcap with timeout - c

I want to write a small application using Libpcap in C on Linux.
Currently, it starts to sniff and wait for the packets. But that's not what I need actually. I want it to wait for N seconds and then stop listening.
How can I achieve that?
Here is my code:
void got_packet(u_char *args, const struct pcap_pkthdr *header, const u_char *packet)
{
printf("got packet\n);
}
int main()
{
int ret = 0;
char *dev = NULL; /* capture device name */
char errbuf[PCAP_ERRBUF_SIZE]; /* error buffer */
pcap_t *handle; /* packet capture handle */
char filter_exp[] = "udp dst port 1500"; /* filter expression */
struct bpf_program fp; /* compiled filter program (expression) */
bpf_u_int32 mask; /* subnet mask */
bpf_u_int32 net; /* ip */
int num_packets = 10; /* number of packets to capture */
/* get network number and mask associated with capture 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;
}
/* print capture info */
printf("Device: %s\n", dev);
printf("Number of packets: %d\n", num_packets);
printf("Filter expression: %s\n", filter_exp);
/* open capture device */
handle = pcap_open_live(dev, SNAP_LEN, 1, 1000, errbuf);
if (handle == NULL) {
fprintf(stderr, "Couldn't open device %s: %s\n", dev, errbuf);
exit(EXIT_FAILURE);
}
/* compile the filter expression */
if (pcap_compile(handle, &fp, filter_exp, 0, net) == -1) {
fprintf(stderr, "Couldn't parse filter %s: %s\n",
filter_exp, pcap_geterr(handle));
exit(EXIT_FAILURE);
}
/* apply the compiled filter */
if (pcap_setfilter(handle, &fp) == -1) {
fprintf(stderr, "Couldn't install filter %s: %s\n",
filter_exp, pcap_geterr(handle));
exit(EXIT_FAILURE);
}
/* now we can set our callback function */
pcap_loop(handle, num_packets, got_packet, NULL);
/* cleanup */
pcap_freecode(&fp);
pcap_close(handle);
}

You should call pcap_breakloop() when you want stop listening. So one way would be to:
setup an alarm to trigger in N seconds,
install a signal handler for SIGALRM signal,
call pcap_breakloop() inside the handler to make pcap_loop() return.
code:
void alarm_handler(int sig)
{
pcap_breakloop(handle);
}
int main()
{
...
alarm(N);
signal(SIGALRM, alarm_handler);
/* now we can set our callback function */
pcap_loop(handle, num_packets, got_packet, NULL);
/* cleanup */
pcap_freecode(&fp);
pcap_close(handle);
}
Note: As for using libpcap's read timeout to do this, it won't and can't work, man pcap explicitly warns against it:
The read timeout cannot be used to cause calls that read packets to return within a limited period of time [...] This means that the read timeout should NOT be used, for example, in an interactive application to allow the packet capture loop to poll for user input periodically, as there's no guarantee that a call reading packets will return after the timeout expires even if no packets have arrived.

If you look at this page from the tcpdump website, you can see the follwing:
Opening the device for sniffing
The task of creating a sniffing session is really quite simple. For this, we use pcap_open_live(). The prototype of this function (from the pcap man page) is as follows:
pcap_t *pcap_open_live(char *device, int snaplen, int promisc, int to_ms,
char *ebuf)
The first argument is the device that we specified in the previous section. snaplen is an integer which defines the maximum number of bytes to be captured by pcap. promisc, when set to true, brings the interface into promiscuous mode (however, even if it is set to false, it is possible under specific cases for the interface to be in promiscuous mode, anyway). to_ms is the read time out in milliseconds (a value of 0 means no time out; on at least some platforms, this means that you may wait until a sufficient number of packets arrive before seeing any packets, so you should use a non-zero timeout). Lastly, ebuf is a string we can store any error messages within (as we did above with errbuf). The function returns our session handler.
If this does not work, let us know.

I have been studying and testing these code fragments for a while. Somewhere, I noticed the observation that when you exit pcap_loop, although you may have seen packets, the exit conditions suggest that you have seen none. I assume from this that all the processing of the packet must occur in the scope of the callback function. So if I want to reset quickly and be ready for another packet, I will need to spawn another process to work on each packet.

Old post but I was researching and came across this.
From the man page for pcap_loop() it specifically says, "It does not return when live read timeouts occur; instead, it attempts to read more packets."
But the man pages for pcap_dispatch() and pcap_next() both indicate they return on timeout.

Related

Cannot capture the packet using libpcap

I am kind of new to use libpcap.
I am using this library to capture the packet and the code i wrote to the capture the packet is below.
The interface that I am tapping is always flooded with arp packet so there is always packet coming to the interface.But I cannot able to tap these packet. The interface is UP and running.
I got no error on pcap_open_live function.
The code is in C. And I am running this code on FreeBSD10 machine 32 bit.
void captutre_packet(char* ifname , int snaplen) {
char ebuf[PCAP_ERRBUF_SIZE];
int pflag = 0;/*promiscuous mode*/
snaplen = 100;
pcap_t* pcap = pcap_open_live(ifname, snaplen, !pflag , 0, ebuf);
if(pcap!=NULL) {
printf("pcap_open_live for %s \n" ,ifname );
}
int fd = pcap_get_selectable_fd(pcap);
pcap_setnonblock(pcap, 1, ebuf);
fd_set fds;
struct timeval tv;
FD_ZERO(&fds);
FD_SET(fd, &fds);
tv.tv_sec = 3;
tv.tv_usec = 0;
int retval = select(fd + 1, &fds, NULL, NULL, &tv);
if (retval == -1)
perror("select()");
else if (retval) {
printf("Data is available now.\n");
printf("calling pcap_dispatch \n");
pcap_dispatch(pcap , -1 , (pcap_handler) callback , NULL);
}
else
printf("No data within 3 seconds.\n");
}
void
callback(const char *unused, struct pcap_pkthdr *h, uint8_t *packet)
{
printf("got some packet \n");
}
I am always getting retval as 0 which is timeout.
I don't know what is happening under the hood I follow the tutorial and they also did exactly the same thing I do not know what i am missing.
I also want to understand how the packet from the ethernet layer once received get copied into this opened bpf socket/device (using pcap_open_live) and how the buffer is copied from kernel space to user space?
And for how long we can tap the packet till the kernel consume or reject the packet?
The pcap_open_live() call provided 0 as the packet buffer timeout value (the fourth argument). libpcap does not specify what a value of 0 means, because different packet capture mechanisms, on different operating systems, treat that value differently.
On systems using BPF, such as the BSDs and macOS, it means "wait until the packet buffer is completely full before providing the packets. If the packet buffer is large (it defaults to about 256K, on FreeBSD), and the packets are small (60 bytes for ARP packets), it may take a significant amount of time for the buffer to fill - longer than the timeout you're handing to select().
It's probably best to have a timeout value of between 100 milliseconds and 1 second, so pass an argument of somewhere between 100 and 1000, not 0.

Getting Ethernet frame length on raw socket(nonblocking)

I am trying to send and receive raw ethernet frames to include a network device as a media access controller in a simulation environment.
Therefore it is important that the receiving of the packets works through nonblocking statements.
Now the sending of the raw ethernet frames works fine but there's one thing about the receive path that is confusing me:
How do I know where the one frame ends and the other frame begins.
What I fundamentally do is to open a raw socket:
device.socket = socket(AF_PACKET, SOCK_RAW, IPPROTO_RAW);
setting it up as non blocking:
flags = fcntl(s,F_GETFL,0);
assert(flags != -1);
fcntl(s, F_SETFL, flags | O_NONBLOCK);
and then call the recv() function cyclical to get the data from the socket:
length = recv(s, buffer, ETH_FRAME_LEN_MY, 0);
But as far as I know the recv() function only returns the amount of bytes, that is currently availible in the receive buffer and therefore I do not know if another frame starts or if I am still reading the "old" packet.
And because of the fact, that the length of the ethernet frame is not included in the header I can not do this on my own.
Thank you in advance!
If anyone runs into the same problem here's a possible solution:
You can use the libpcap library(in windows winpcap) to open the device as a capture device:
char errbuf[PCAP_ERRBUF_SIZE]; /* error buffer */
Pcap_t *handle; /* packet capture handle */
/* open capture device*/
/* max possible length, not in promiscous mode, no timeout!*/
handle = pcap_open_live(dev, 65536, 0, 0, errbuf);
if (handle == NULL) {
fprintf(stderr, "Couldn't open device %s: %s\n", dev, errbuf);
}
/* set capture device to non blocking*/
if(pcap_setnonblock(pcap_t *p, int nonblock, char *errbuf)){
fprintf("Could not set pcap interface in non blocking mode: %s \n", errbuf);
}
Now you can cyclic call the pcap_dispatch function to receive packet(s):
int pcap_dispatch(pcap_t *p, int cnt, pcap_handler callback, u_char *user);
You have to provide a callback function in which the data is handled.
See https://www.freebsd.org/cgi/man.cgi?query=pcap_dispatch&apropos=0&sektion=3&manpath=FreeBSD+11-current&format=html for further information.
You can send raw ethernet frames by using the inject function:
pcap_inject(pcap,frame,sizeof(frame));

Why is pcap_datalink() always returning 1 (Ethernet), even on wireless device?

I'm having an issue where by pcap_datalink() is always returning 1. To my understanding this is LINKTYPE_ETHERNET. But, the device I am using is a wireless card and in my case en0.
This is stopping me from putting the card into monitor mode, and stopping my WLAN filters from working. I've tried to run this on both OSX and Linux with the same results. I also run as root.
Here's the part of my code that's causing the problem. For the example, assume dev is set to en0 (wireless device on Mac).
#include <stdio.h>
#include <pcap.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
pcap_t *pcap_h;
char *dev, errbuf[PCAP_ERRBUF_SIZE];
struct bpf_program fp;
struct pcap_pkthdr header;
const u_char *packet;
if(argc < 2)
{
printf("Usage: %s device\n", argv[0]);
exit(EXIT_FAILURE);
}
dev = argv[1];
if((pcap_h = pcap_create(dev, errbuf)) == NULL)
{
printf("pcap_create() failed: %s\n", errbuf);
exit(EXIT_FAILURE);
}
if(pcap_can_set_rfmon(pcap_h) == 0)
{
printf("Monitor mode can not be set.\n");
}
if(pcap_set_rfmon(pcap_h, 1) != 0)
{
printf("Failed to set monitor mode.\n");
exit(EXIT_FAILURE);
}
if(pcap_activate(pcap_h) != 0)
{
printf("pcap_activate() failed\n");
exit(EXIT_FAILURE);
}
/*
* Compile a filter to sniff 802.11 probe requests
* Filter: type mgt subtype probe-req
*/
if(pcap_compile(pcap_h, &fp, "type mgt subtype probe-req", 0, PCAP_NETMASK_UNKNOWN) == -1)
{
printf("pcap_compile() failed: %s\n", pcap_geterr(pcap_h));
exit(EXIT_FAILURE);
}
/*
* Set the compiled filter
*/
if(pcap_setfilter(pcap_h, &fp) == -1)
{
printf("pcap_setfilter() failed: %s\n", pcap_geterr(pcap_h));
exit(EXIT_FAILURE);
}
pcap_freecode(&fp);
packet = pcap_next(pcap_h, &header);
printf("Header: %d\n", header.len);
pcap_close(pcap_h);
return 0;
}
Any idea's why pcap_datalink() is always returning 1?
Edit
Updated code, and added pcap_set_rfmon() before the call to pcap_activate(). I get an error:
pcap_compile() failed: 802.11 link-layer types supported only on 802.11
Are you shure this is what's is stopping you from putting the card into monitor mode, and stopping your WLAN filters from working, or do you do this call to pcap_datalink() as a check trying to pinpoint the issue?
Be aware that, from PCAP-LINKTYPE(7):
For a live capture or ``savefile'', libpcap supplies, as the
return value of the pcap_datalink(3PCAP) routine, a value that
indicates the type of link-layer header at the beginning of the
packets it provides. This is not necessarily the type of link-layer
header that the packets being captured have on the network from
which they're being captured; for example, packets from an IEEE 802.11
network might be provided by libpcap with Ethernet headers that
the network adapter or the network adapter driver generates from the
802.11 headers.
So I would not take this LINKTYPE_ETHERNET / DLT_EN10MB return value as the sure indication of a problem here.
EDIT:
Also, pcap_set_rfmon() is supposed to be call before the handle is activated, which is not visible in your code.
pcap is rather touchy about the order things should be done. Have a look at the man pages for pcap_can_set_rfmon and pcap_set_rfmon.
The order should be:
pcap_create
pcap_can_set_rfmon
pcap_set_rfmon (if so far so good)
then and only then, pcap_activate

pcap_loop does just wait

I'm trying to do a little sniffer using pcap in C like explained here
My problem is that pcap_loop absolutly catch no packets and/or does nothing, my callback function is never called. my guess was the time out value but even if i set it to 20 (ms), nothing changes. It hope it s only a simple error i can't see, but i'll let you guys try to figure it out, cause it's been messing my brain too much !!
Thanks
Nikko
Edit : i choose wlan0 as interface and it works with the program given at the link
My main :
int main(int argc, char* argv[]) {
// interface & err buff
char *dev, errbuff[PCAP_ERRBUF_SIZE];
int i = 0,inum= -1;
// it filters out only packet from this machin
char filter_exp[] = "ip host localhost";
struct bpf_program fp; /* compiled filter program (expression) */
/* typedef, no need for struct ... */
bpf_u_int32 mask;
bpf_u_int32 net;
int num_packets = 10;
// 1.0+ API pcap version
pcap_if_t * alldevs;
pcap_if_t * pdev;
pcap_t * handle;
// 1st argument interface
if(argc == 2) {
dev = argv[1];
printf("Chosen interface : %s\n",dev);
}
//+1.0 api version
if(pcap_findalldevs(&alldevs,errbuff)){
fprintf(stderr,"findalldev failed to retrieve interface\n %s",errbuff);
return(2);
}
if(alldevs == NULL){
fprintf(stderr,"Retrieved interface is null\n");
return(2);
}
// select all interfaces
for(pdev = alldevs; pdev != NULL;pdev = pdev->next) {
printf("Device %d : ",++i);
print_pcap_if_t(pdev);
//print_pcap_addr(pdev->addresses);
}
printf("Enter the interface number (1-%d):",i);
scanf("%d", &inum);
if(inum < 1 || inum > i){
fprintf(stderr,"Device %d not in list.\n",i);
return(2);
}
/* Jump to the selected adapter */
for(pdev=alldevs, i=0; i< inum - 1 ;pdev=pdev->next, i++);
printf("\n-------------------------------------------------\n");
//printf("Chosen device : %s",pdev->name);
//print_pcap_if_t(pdev);
/* activate device */
printf("activating\n");
handle = pcap_open_live(pdev->name,SNAP_LEN,1,1000,errbuff);
if(handle == NULL){
fprintf(stderr,"Could not open device for sniffing");
return(2);
}
/* compile filter */
if(pcap_compile(handle,&fp,filter_exp,0,net) == -1) {
fprintf(stderr,"Could not compile filtering rules");
return(EXIT_FAILURE);
}
/* apply filter */
if(pcap_setfilter(handle,&fp) == -1) {
fprintf(stderr,"Could not set filtering rules");
return(EXIT_FAILURE);
}
printf("Waiting for packets to come in your hands");
fflush(stdout);
pcap_loop(handle,num_packets,got_packet,NULL);
pcap_freecode(&fp);
pcap_close(handle);
pcap_freealldevs(alldevs);
return(0);
}
ip host localhost
"localhost" is the name for the IP address 127.0.0.1; it is not the IP address of your machine on the Internet, it's a special IP address used to send IPv4 packets from your machine to itself (e.g., "ftp localhost" if you want to test the FTP server on your machine by connecting to it from a command prompt on your machine).
Traffic to or from other hosts will not come from, or be sent, to, 127.0.0.1.
If your machine has the IP address 10.0.1.2, for example, try "ip host 10.0.1.2".
Ok i found the problem :
my filter "ip host localhost" aws the reason. I changed it to "ip" and there it was =)
I dont really understand though. What i do is i launch the program, and just refresh a web page after that. So my first request is a GET or stg, with source = localhost , no ? And the response will contains my address also in the destination field. According to man page :
host HOST True if either the IPv4/v6 source or destination of the packet is
HOST.
Would it be that it does no translation of "localhost" when setting the filter ?
Anyway , i hope it could help some others...

How to allocate a memory to send a large pcap file (of size larger than available memory) with high performance using winpcap?

I have used the code from winpcap example to send pcap file(original code from winpcap documenation found at this link)
It works fine to send a small pcap files but if I tried to send a large pcap file (larger than available memory size say 2 Gb) it will fail for sure. This code is used to allocate size of the file in memory in order to send it later
caplen= ftell(capfile)- sizeof(struct pcap_file_header);
...
/* Allocate a send queue */
squeue = pcap_sendqueue_alloc(caplen);
The question is how to make this work for large files(in Gb or larger than maximum memory space available for allocation)? Should I allocate only 100 Mb for example and send the queue and then take the next 100Mb? If yes what is the proper buffer size? And how to do this?
an important issue here is the performance of sending this file which needed to be done as fast as can (i am sending a video packets).
In short how to manage the memory here to achieve this goal?
Would anyone have a proper solution or suggestion?
Snippet from example code (unnecessary code for this question replaced by ... )
...
#include <pcap.h>
#include <remote-ext.h>
...
void main(int argc, char **argv)
{
pcap_t *indesc,*outdesc;
...
FILE *capfile;
int caplen, sync;
...
pcap_send_queue *squeue;
struct pcap_pkthdr *pktheader;
u_char *pktdata;
...
/* Retrieve the length of the capture file */
capfile=fopen(argv[1],"rb");
if(!capfile){
printf("Capture file not found!\n");
return;
}
fseek(capfile , 0, SEEK_END);
caplen= ftell(capfile)- sizeof(struct pcap_file_header);
fclose(capfile);
...
...
/* Open the capture file */
if ( (indesc= pcap_open(source, 65536, PCAP_OPENFLAG_PROMISCUOUS, 1000, NULL, errbuf) ) == NULL)
{
fprintf(stderr,"\nUnable to open the file %s.\n", source);
return;
}
/* Open the output adapter */
if ( (outdesc= pcap_open(argv[2], 100, PCAP_OPENFLAG_PROMISCUOUS, 1000, NULL, errbuf) ) == NULL)
{
fprintf(stderr,"\nUnable to open adapter %s.\n", source);
return;
}
...
/* Allocate a send queue */
squeue = pcap_sendqueue_alloc(caplen);
/* Fill the queue with the packets from the file */
while ((res = pcap_next_ex( indesc, &pktheader, &pktdata)) == 1)
{
if (pcap_sendqueue_queue(squeue, pktheader, pktdata) == -1)
{
printf("Warning: packet buffer too small, not all the packets will be sent.\n");
break;
}
npacks++;
}
if (res == -1)
{
printf("Corrupted input file.\n");
pcap_sendqueue_destroy(squeue);
return;
}
/* Transmit the queue */
if ((res = pcap_sendqueue_transmit(outdesc, squeue, sync)) < squeue->len)
{
printf("An error occurred sending the packets: %s. Only %d bytes were sent\n", pcap_geterr(outdesc), res);
}
/* free the send queue */
pcap_sendqueue_destroy(squeue);
/* Close the input file */
pcap_close(indesc);
/*
* lose the output adapter
* IMPORTANT: remember to close the adapter, otherwise there will be no guarantee that all the
* packets will be sent!
*/
pcap_close(outdesc);
return;
}
Just cap it at say 50 MB (this is a somewhat arbitrary but I think reasonable starting point), and enhance the bit of code that warns when not all the packets fit in the queue so that it just sends what it has so far and starts filling the queue from the beginning with the remaining packets.

Resources