C language based on Linux LIBPCAP implementation of packet capture program

Source: Internet
Author: User
Tags string format


C language-based LIBPCAP implementation of a packet capture program process
The overall architecture of the Pcap-based sniffer program is as follows: (1) First decide which interface to use to start sniffing. In Linux, this could be eth0, while in the BSD system it could be xl1 and so on. We can also use a string to define the device, or use the interface name provided by Pcap to work. (...

The overall architecture of the Pcap-based sniffer program, with the following flow:

(1) First decide which interface to use to start sniffing. In Linux, this could be eth0, while in the BSD system it could be xl1 and so on. We can also use a string to define the device, or use the interface name provided by Pcap to work.

(2) initialization of PCAP. Here you need to tell pcap what device to sniff. If you want, we can also sniff multiple devices. How do you differentiate them? Use a file handle. Just like opening a file for reading and writing, we have to name our sniffer "session" so that they can differentiate themselves from each other.

(3) If you only want to sniff specific transmissions (such as TCP/IP packets, packets destined for port 23, etc.), we must create a rule collection, compile and use it. The process is divided into three closely interrelated phases. The rule set is placed inside a string and is converted into a format that can be read pcap (hence compiling it). Compiling is actually invoking a function in our program that is not used by an external program. Next we'll tell Pcap to use it to filter out the conversation we want. (This step is optional)

(4) Finally, we tell PCAP to enter its main execution loop. During this phase Pcap worked until it received all the packages we wanted. Whenever it receives a package and invokes another already defined function, this function can do whatever work we want, it can parse the Suobu received package and print the result to the user, it can save the result as a file, or do nothing at all.

(5) After sniffing the required data, we close the session and end it.

Programming implementation process:

(1) Setting up the device

This is very simple. There are two ways to set up devices that you want to sniff.

First, we can simply let the user tell us. Examine the following procedure:

#include <stdio.h> #include <pcap.h>int main (int argc, char *argv[]) {char *dev = argv[1];p rintf ("Device:%s", dev); return (0);}

Run:

[Email protected]/h/jiabei# vim a1.c

[Email protected]/h/jiabei# gcc A1.c-lpcap

[Email protected]/h/jiabei#./a.out

Device: (NULL) (output)

The user specifies a device by passing it to the first parameter of the program. The string "Dev" preserves the name of the interface we want to sniff (of course, the user must give us a really existing interface) in a format that pcap can "understand".

The other is the same simplicity. To see this procedure:

#include <stdio.h> #include <pcap.h>int main () {char *dev, errbuf[pcap_errbuf_size];d ev = Pcap_lookupdev ( ERRBUF);p rintf ("Device:%s", dev); return (0);}

Run:[email protected]/h/jiabei# vim a2.c
[email protected]/h/jiabei# gcc A2.c-lpcap
error: ' Errbuf ' undeclared .... (output)
we found that the errbuf[] array is undefined. so:
#include <stdio.h> #include <pcap.h>char errbuf[pcap_errbuf_size];int main () {char *dev, ERRBUF[PCAP_ Errbuf_size];d ev = Pcap_lookupdev (errbuf);p rintf ("Device:%s", dev); return (0);}
Run again:[email protected]/h/jiabei# vim a2.c
[email protected]/h/jiabei# gcc A2.c-lpcap
device:eth0 (output, which is the default eth0 port under Linux)
(2) Turn on the device for sniffing

The task of creating a sniffer session is really simple. To do this, we use the pcap_open_live () function. The prototype of this function (according to PCAP's manual page) is as follows:

1 pcap_t *pcap_open_live (Char *device,intSnaplen,intPromisc,intTo_ms,Char*ebuf)

The first parameter is the device that we specified in the previous section, Snaplen is shaped, and it defines the maximum number of bytes that will be captured by the pcap. When Promisc is set to true, it is possible to set the specified interface to promiscuous mode (however, an extraordinary case where the interface is still in promiscuous mode when it is false). The To_ms is the time-out value of the read, in milliseconds (assuming 0 is sniffing until the error occurs, and 1 is indeterminate). Finally, Ebuf is a string that we can deposit any error message (just like the errbuf above). This function returns its session handle.

The difference between promiscuous and non-promiscuous modes: These two approaches are quite different. Generally, in a non-promiscuous sniffer, the host only sniffs traffic that is directly related to it, such as the ones that are sent to it, from it, or routed by it, are captured by the sniffer. In promiscuous mode, all traffic on the transmission line is sniffed. In a non-switched network, this will be the communication across the network. The most obvious advantage of this is that more packets are sniffed, and they are either helpful or not because of the reason you sniff the network. However, promiscuous mode is detectable. A host can determine whether another host is sniffing in promiscuous mode with high-intensity testing. Second, it works only in a non-switched network environment (such as a hub, or an ARP level in an interchange). Again, in a high-load network, the host's system resources will be consumed very seriously.

(3) Filter communication

The implementation of this process is done by Pcap_compile () and Pcap_setfilter ().

It must be compiled before using our own filters. The filter expression is saved in a string (a character array). Its syntax is proven to be very good in Tcpdump's hand albums. I suggest you read it yourself. But we will use simple test expressions so that you can easily understand my example.

We call Pcap_compile () to compile it, and its prototype is defined like this:

1 intPcap_compile (pcap_t *p, strUCt bpf_program *FP,Char *str,intoptimize, Bpf_u_int32 netmask)

The first argument is a session handle. Next is a reference to the address where we store the compiled filter version. The next is the expression itself, stored in the specified string format. The bottom is a volume that defines whether the expression is optimized (0 is false,1 to true, standard). Finally, we must specify the netmask that applies this filter. The function returns 1 as a failure, and any other value indicates success.

After the expression is compiled, it can be used. Now enter Pcap_setfilter (). As we introduce the PCAP format, let's take a look at the prototype of Pcap_setfilter ():

1 int pcap_setfilter (pcap_t *p, struct bpf_program *fp)

This is very intuitive, the first parameter is the session handle, the second argument is a reference to the version of the expression being compiled (it can be inferred that it is the same as the second parameter of Pcap_compile ()).

The following code example might give you a better understanding of:

#include <pcap.h>int main () {pcap_t *handle;/* The handle of the session */char dev[] = "eth0";/* device to perform sniffer */char Errbuf[pcap_errbuf_siz E]; /* String that stores error information */struct Bpf_program filter; /* Compiled filter expression */char filter_app[] = "Port 23"; /* Filter Expression */bpf_u_int32 mask; /* netmask */bpf_u_int32 net of the device performing the sniffer; /* IP address of the device performing the sniffer */pcap_lookupnet (Dev, &net, &mask, errbuf); handle = Pcap_open_live (Dev, bufsiz, 1, 0, ERRBUF);p CA P_compile (handle, &filter, Filter_app, 0, net);p Cap_setfilter (handle, &filter);}

This program makes the sniffer sniff all traffic through port 23, using promiscuous mode, the device is eth0.

(4) The actual sniffing

There are two ways to capture a package. We can capture only one package at a time, or we can enter a loop, and so on to capture multiple packages and then process them. We'll look at how to capture a single package first, and then look at how to use loops. To do this, we use the function Pcap_next ().

The prototype of Pcap_next () and its simplicity:

U_char *pcap_next (pcap_t *p, struct PCAP_PKTHDR *h)

The first argument is the session handle, and the second parameter is a pointer to a struct that includes the overall information about the current packet (the time it was captured, the length of the package, the length of its specified part), and only one fragment here, just as an example. Pcap_next () returns a U_char pointer to the package described by the struct. We will discuss this method of actually reading the package itself later.

Here's an example that shows how to sniff a package using Pcap_next ():

#include <pcap.h> #include <stdio.h>int main () {pcap_t *handle;/* session handle */char *dev;/* Perform sniffer device */char errbuf[pc Ap_errbuf_size]; /* String that stores error information */struct Bpf_program filter; /* Already compiled filter */char filter_app[] = "Port 23"; /* Filter Expression */bpf_u_int32 mask; /* Mask */bpf_u_int32 net of the network; /* The IP address of the host */struct PCAP_PKTHDR header; /* defined */const U_char *packet by Pcap.h; /* Actual package *//* Define the device */dev = Pcap_lookupdev (ERRBUF);/* Probe device properties */pcap_lookupnet (Dev, &net, &mask, Errbuf) ;/* Open session in promiscuous mode */handle = pcap_open_live (Dev, bufsiz, 1, 0, ERRBUF);/* Compile and Apply filter */pcap_compile (handle, &filter, Filter_ App, 0, net);p Cap_setfilter (handle, &filter);/* intercepts a package */packet = Pcap_next (handle, &header);/* Prints its length */printf (" Jacked a packet with length of [%d] ", header.len);/* Close session */pcap_close (handle); return (0);}

Run:[Email protected]/h/jiabei# vim a3.c
[email protected]/h/jiabei# gcc A3.c-lpcap
Jacked a packet with length of [1]
(output)


This program sniffs the device returned by Pcap_lookupdev () and resets it to promiscuous mode. It finds that the first packet passes through port (telnet) and tells the user the size (in bytes) of the packet.


C language based on Linux LIBPCAP implementation of packet capture program

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.