Some time ago, because I had to write a router program myself, I began to learn libpcap and netlink. I also read articles written by many cool people on the Internet, we found that the pcap and netlink materials in Chinese are quite few (in comparison, pcap may be a little more, and netlink is almost none ). So I decided to write a few articles and share them with you. Libpcap is
Some time ago, because I had to write a router program myself, I began to learn libpcap and netlink. I also read articles written by many cool people on the Internet, we found that the pcap and netlink materials in Chinese are quite few (in comparison, pcap may be a little more, and netlink is almost none ). So I decided to write a few articles and share them with you.
Libpcap is a grouping and capturing function library provided by the operating system for access unrelated to the implementation. Currently, it only supports group reading. after adding some code, you can also write data link groups (if someone has any questions about the sentence, go to the late Richard Steven to discuss it, he said: P ).
Libcap supports most Unix systems, of course also supports Linux, and is integrated in the current linux release version.TcpdumpIt is used. Libcap is composed of about 25 functions. here I will only introduce the simple usage. As for the in-depth research, enter man 3 pcap in linux.
One thing to note is that libpcap is used to capture Ethernet packets. I don't think it is possible to capture packets of ppp links, because I have read a program to capture packets in a VPC, people write a class specifically to read com devices. As for why I can't do it in theory, it's hard for me to say why. when I figure it out, I can write another blog.
Let's get started! Look at our first program ....
# Include
# Include
# Include
# Include
# Include
# Include
# Include
Int main (int argc, char ** argv)
{
Char * dev;
Char * net;
Char * mask;
Int ret;
Char errbuf [PCAP_ERRBUF_SIZE];
Bpf_u_int32 netp;
Bpf_u_int32 maskp;
Struct in_addr addr;
Dev = pcap_lookupdev (errbuf );
If (dev = NULL)
{
Printf ("% s \ n", errbuf );
Exit (1 );
}
Printf ("DEV: % s \ n", dev );
Ret = pcap_lookupnet (dev, & netp, & maskp, errbuf );
, Because the second parameter of the pcap_lookupnet function does not obtain an ip address but a network number. you can check that your mask is 255.255.255.0 and the ip address is 192.168.1.3. Therefore, the network number is 192.168.1.0.
If (ret =-1)
{
Printf ("% s \ n", errbuf );
Exit (1 );
}
Addr. s_addr = netp; // An IPv4 address formatted as au_long
Net = inet_ntoa (addr); // returns the pointer to the dot-decimal string in the static memory, converting the network address to the dot-separated string format
If (net = NULL)
{
Perror ("inet_ntoa ");
Exit (1 );
}
Printf ("NET: % s \ n", net );
Addr. s_addr = maskp;
Mask = inet_ntoa (addr );
If (mask = NULL)
{
Perror ("inet_ntoa ");
Exit (1 );
}
Printf ("MASK: % s \ n", mask );
Return 0;
}
Then gcc-o pcap_1 pcap_1.c-lpcap (must be the-lpcap parameter)
Compile OK ~, Run./pcap_1 and you can see:
DEV: eth0
NET: 192.168.12.0
MASK: 255.255.255.0
Okay, the first pcap program is released .....
But (of course, but what else I will write later), the above program did nothing except show US pcap_lookupdev and pcap_lookupnet. well, let's continue, write our first packet capture program.
# Include
# Include
# Include
# Include
# Include
# Include
# Include
# Include
Int main (int argc, char ** argv)
{
Int I;
Char * dev;
Charerrbuf [PCAP_ERRBUF_SIZE];
Pcap_t * descr;
Const u_char * packet;
Struct pcap_pkthdrhdr;
Struct ether_header * eptr;
U_char * ptr;
Dev = pcap_lookupdev (errbuf );
If (dev = NULL)
{
Printf ("% s \ n", errbuf );
Exit (1 );
}
Printf ("DEV: % s \ n", dev );
Descr = pcap_open_live (dev, BUFSIZ, 0,-1, errbuf );
Function name: pcap_t * pcap_open_live (char * device, int snaplen, intpromisc, int to_ms, char * ebuf)
Function: Get the description of the packet capture used to capture network packets.
Parameter description: The device parameter specifies the name of the network device that is enabled. The snaplen parameter defines the maximum number of bytes of captured data. Promisc specifies whether to place network interfaces in hybrid mode. The to_ms parameter * specifies the timeout time (in milliseconds ). The ebuf parameter is used to pass error messages only when the pcap_open_live () function returns NULL.
If (descr = NULL)
{
Printf ("pcap_open_live (): % s \ n", errbuf );
Exit (1 );
}
Packet = pcap_next (descr, & hdr );
// Capture data packets
If (packet = NULL)
{
Printf ("Didn't grab packet \ n ");
Exit (1 );
}
Printf ("Grabbed packet oflength % d \ n", hdr. len );
Printf ("Recieved at... % s \ n", ctime (const time_t *) & hdr. ts. TV _sec ));
Printf ("Ethernet address lengthis % d \ n", ETHER_HDR_LEN );
Eptr = (struct ether_header *) packet;
////////
StructEther_header {
U_charEther_dhost [ETHER_ADDR_LEN];
U_charEther_dhost [ETHER_ADDR_LEN];
U_shortEther_type;
};
Here, ETHER_ADDR_LEN is defined as 6, if the previous layer is IP protocol. The value of ether_type is 0x0800;
# DefineETHERTYPE_IP Zero x 0800
# DefineETHERTYPE_ARP Zero x 0806
# DefineETHERTYPE_REVARPZero x 8035
# DefineETHERTYPE_VLAN Zero x 8100
# DefineETHERTYPE_IPV6 0x86dd
# DefineETHERTYPE_LOOPBACKZero x 9000
U_char Etherbroadcastaddr [6] = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff}; broadcast mac addresses are all 1
*////////
If (ntohs (eptr-> ether_type) = ETHERTYPE_IP)
{
Printf ("Ethernet type hex: % x dec: % d is an IP packet \ n ",
Ntohs (eptr-> ether_type ),
Ntohs (eptr-> ether_type ));
} Else If (ntohs (eptr-> ether_type) = ETHERTYPE_ARP)
{
Printf ("Ethernet type hex: % x dec: % d is an ARP packet \ n ",
Ntohs (eptr-> ether_type ),
Ntohs (eptr-> ether_type ));
} Else {
Printf ("Ethernet type % x not IP", ntohs (eptr-> ether_type ));
Exit (1 );
}
Ptr = eptr-> ether_dhost;
I = ETHER_ADDR_LEN;
Printf ("DestinationAddress:");
Do {
Printf ("% s % x", (I = ETHER_ADDR_LEN )? "": ":", * Ptr ++ );
} While (-- I> 0 );
Printf ("\ n ");
Ptr = eptr-> ether_shost;
I = ETHER_ADDR_LEN;
Printf ("SourceAddress:");
Do {
Printf ("% s % x", (I = ETHER_ADDR_LEN )? "": ":", * Ptr ++ );
} While (-- I> 0 );
Printf ("\ n ");
Return 0;
}
All right, compile and run it!
[Root @ norman libpcap] #./pcap_2
DEV: eth0
Grabbed packet of length 76
Recieved at time... Mon Mar 12 22:23:29 2001
Ethernet address length is 14
Ethernet type hex: 800 dec: 2048 is an IP packet
Destination Address: 0: 20: 78: d1: e8: 1
Source Address: 0: a0: cc: 56: c2: 91
[Root @ pepe libpcap] #
Someone may have waited for half a day without a package. there is a good way to open another console and ping a website, such as google ~~, Haha
Now there is a response ~~
This program is written by a foreigner. let's see if there is no problem with the annotations ~
But we also found a problem, that is, the above program can only capture one package. what should we do if we keep capturing the package? what should we do with loops ?? Libpcap provides a better method:
Int pcap_loop (pcap_t * p, int cnt, pcap_handler callback, u_char * user );
This function can continuously capture Ethernet packets. cnt is the number of captures, and callback is the processing function. how to write this processing function? you can see pcap_3.c. What is the user parameter? Don't ask me. I don't know either.
# Include
# Include
# Include
# Include
# Include
# Include
# Include
# Include
Void my_callback (u_char * useless, const struct pcap_pkthdr * pkthdr, const u_char *
Packet)
{
Static int count = 1;
Fprintf (stdout, "% d,", count );
If (count = 4)
Fprintf (stdout, "Come on baby sayyy you love me !!! ");
If (count = 7)
Fprintf (stdout, "Tiiimmmeesss !! ");
Fflush (stdout );
Count ++;
}
Int main (int argc, char ** argv)
{
Int I;
Char * dev;
Charerrbuf [PCAP_ERRBUF_SIZE];
Pcap_t * descr;
Const u_char * packet;
Struct pcap_pkthdrhdr;
Struct ether_header * eptr;
If (argc! = 2) {fprintf (stdout, "Usage: % s numpackets \ n", argv [0]); return 0 ;}
Dev = pcap_lookupdev (errbuf );
If (dev = NULL)
{Printf ("% s \ n", errbuf); exit (1 );}
Descr = pcap_open_live (dev, BUFSIZ, 0,-1, errbuf );
If (descr = NULL)
{Printf ("pcap_open_live (): % s \ n", errbuf); exit (1 );}
Pcap_loop (descr, atoi (argv [1]), my_callback, NULL );
/////
Function name: int pcap_loop (pcap_t * p, int cnt, pcap_handlercallback, uchar * user); function: capture data packets without responding to the timeout parameter set by pcap_open_live: p is the pointer of the NIC returned by pcap_open_live (); cnt is used to set the number of captured packets; pcap_handler is a parameter used with voidpacket_handler (), that is, the name of the callback function; the user value is generally NULL.
Third, the prototype of the callback function is as follows:
Pcap_callback (u_char * argument, const struct pcap_pkthdr * packet_header, const u_char * packet_content)
The pcap_content parameter indicates the content of the captured data packet.
The argument parameter is passed from the pcap_loop () function.Note: the parameter here refers to the * user parameter in pcap_loop.
The pcap_pkthdr parameter indicates the basic information of the captured data packet, including the time and length.
In addition, the callback function must be a global function or a static function, and its parameter defaults. for example, pcap_loop () can be written
Pcap_loop (pcap_handle, 10, pcap_callback, NULL) cannot pass real parameters to it.
Bytes -----------------------------------------------------------------------------------------------------------------
The parameters of pcap_loop and callback are related:
The last user parameter of pcap_loop is reserved for users. when callback is called, this value is passed to the first parameter (also called user) of callback ), the last parameter p of callback points to a memory space, which stores the packets captured by pcap_loop. The second parameter of callback is a struct pointer, which is defined as follows:
Struct pcap_pkthdr {
Struct timeval ts;
Bpf_u_int32 caplen;
Bpf_u_int32 len;
};
This struct is filled by pcap_loop and used to obtain information about data packets.
Therefore, only the first user pointer in the callback function can be reserved for users. if you want to pass your own parameters to callback, you can only use the last user parameter in pcap_loop.
/////
Fprintf (stdout, "\ nDone processingpackets... wheew! \ N ");
Return 0;
}
Run./pcap_37
1, 2, 3, 4, Come on baby sayyy you love me !!! 5, 6, 7, Tiiimmmeesss !!
Done processing packets... wheew!
Pcap_loop is really easy to use, but if there is no package, just wait there, pcap_dispatch contains a timeout function. Below is a passage in man:
Pcap_dispatch () is used to collect and process packets. cntspecifies the maximum number of packets to process beforereturning. A cnt of-1 processes all the packets encoded Ed in onebuffer. A cnt of 0 processes all packets until an error occurs, EOFis reached, or the read times out (when doing live reads and anon-zero read timeout is specified ). callback specifies a routineto be called with three arguments: a u_char pointer which is passedin from pcap_dispatch (), a pointer to the specified struct (whichprecede the actual network headers and data ), and a u_char pointerto the packet data. the number of packets read is returned. zero isreturned when EOF is reached in A'' savefile. ''A return of-1 indicates an error in which case pcap_perror () or pcap_geterr () maybe used to display the error text.