WinPcap Note 3 Open the adapter and capture the packet

Source: Internet
Author: User
Tags function prototype

In the last lecture, we learned how to get the appropriate information, this one will let us write a program Chiang every packet printed through the adapter.

The function that opens the device is Pcap_open (). function prototypes are

pcap_t* pcap_open (const char* source,int snaplen,int flags,int read_timeout,struct pcap_rmtauth *auth,char * errbuf); '

Pcap_rmatauth

{

int type.

Char *username;;/ /zero-terminated string containing the username that have to is used on the remote machine for authentication

Char *password;

}

snaplen:snaplen Develop which parts of the packet to capture. In some operating systems (such as XBSD and Win32), the driver can be configured to capture only the initialization part of the packet: This reduces the amount of data replicated between applications, thus improving capture efficiency. In this example, we set the value to 65535, which is larger than the maximum MTU we can encounter. Therefore, we are confident that we can always receive complete data packets.

Flags: The most important flag is used to indicate whether the adapter is to be set to promiscuous mode . Typically, the adapter receives only the packets that are sent to it, and the packets that communicate between the other machines are discarded. Conversely, if the adapter is promiscuous, I will capture it regardless of whether the packet is sent to me. That is, I'm going to capture all the packets. This means that in a shared medium (such as a total Linetype Ethernet), WinPcap can capture all the packets from other hosts. Most applications that are used for data capture will set the adapter to promiscuous mode, so we will also use promiscuous mode in the following example.

Pcap_openflag_promiscuous:1, which defines whether the adapter (NIC) enters promiscuous mode (promiscuous modes).    

Pcap_openflag_datatx_udp:2, which defines whether the data transfer (if it is a remote packet) is handled with the UDP protocol.

Pcap_openflag_nocapture_rpcap:4, which defines whether a remote probe captures its own generated packets.

To_ms Specifies the time-out for reading data in milliseconds (1s=1000ms). Read operations on the adapter (for example, with Pcap_dispatch () or PCAP_NEXT_EX ()) respond within To_ms milliseconds, even if no packets are available on the network. in statistical mode ,To_ms can also be used to define the time interval for statistics. Setting To_ms to 0 means that there is no timeout, and if no packet arrives, the read operation will never return. If set to-1, the reverse is true, and the read operation returns immediately, regardless of the arrival of the packet.

read_timeout: in milliseconds. Read timeout is used to set the reading operation to not have to return immediately when encountering a packet, but to wait for some time before more packets arrive and read multiple packets at once from the OS kernel. Not all platforms support read Timeout, which is ignored on platforms that do not support read timeout.

auth: A pointer to ' struct Pcap_rmtauth ' that holds the necessary information when a user logs on to a remote machine. If it is not a remote grab, the pointer is set to NULL.

errbuf: A pointer to the user request buffer that holds the error message when the function is faulted.

The return value is a ' pcap_t ' pointer that can be used as a parameter to the next call (for example, Pcap_compile (), etc.), and a winpcap session that has already been opened is specified. In the case of a problem, it returns null and the ' ERRBUF ' variable holds the error message.

Function 1:

int Pcap_loop (Pcap_t* p,

int CNT,

Pcap_hander Callback,

u_char* User

)

Collect a bunch of packets. Pcap_loop () is similar to Pcap_dispatch (), but it maintains the operation of the read packet until the CNT packet is processed or an error occurs. It does not return when there is an active read timeout. However, specifying a read timeout of non-0 for pcap_open_live () is a better place to call Pcap_dispatch () to receive and process all incoming packets when a time-out occurs. CNT indicates the maximum number of packets to be processed before returning. If CNT is negative, pcap_loop () loops (until an error occurs). Returns 1 if the error occurs, or 0 if CNT is exhausted, or 2 if the abort loop is called before any packets are processed pcap_breakloop (). Therefore, if the program uses Pcap_breakloop (), it must be accurate to determine whether the return value is 1 or 2, but not simply judge the <0.

Function 2:

hypedef void (* Pcap_handler) (u_char* user,

const struct pcap_pkthdr* pkt_header,

Const u_char* Pkt_data)

The callback function prototype that receives the packet. When the user program uses Pcap_dispatch () or Pcap_loop (), the packet is passed to the application using this callback method. A user parameter is a user-defined parameter that contains the state of the capture session, which must match the parameters of Pcap_dispatch () and Pcap_loop (). Pkt_hader is the head associated with the clutch drive. Pkt_data points to the data in the package, including the protocol header.

Structure 1:

struct pcap_pkthdr {

struct Timeval ts;

Bpf_u_int32 Caplen;

Bpf_u_int32 Len;

}

TS: Time stamp

struct Timeval {
Long tv_sec; /* seconds */
Long tv_usec; /* and microseconds */
};

Cpalen: The length of the current grouping

Len: The length of the packet

/*
* Interception of data Packet test. Print out a list of all network adapters, and then select
* Which adapter you want to intercept packets on. The Pcap_loop () function will then intercept
* The packet is passed to the callback function Packet_handler () processing.

* This procedure provides a preliminary understanding of the steps to intercept packets using WINPCAP and some
* Functions and structures that are very important when intercepting packets.
*/

1 //To open an adapter capture packet2#include"Pcap.h"3 4 /*Packet handler function prototype*/5 voidPacket_handler (U_char *param,Const structPcap_pkthdr *header,ConstU_char *pkt_data);6 7 intMain ()8 {9pcap_if_t *Alldevs;Tenpcap_if_t *D; One     intInum; A     inti =0; -pcap_t *Adhandle; -     CharErrbuf[pcap_errbuf_size]; the  -     /*get a list of native devices*/ -     if(PCAP_FINDALLDEVS_EX (pcap_src_if_string, NULL, &alldevs, errbuf) = =-1) -     { +fprintf (stderr,"Error in Pcap_findalldevs:%s\n", errbuf); -Exit1); +     } A  at     /*Print List*/ -      for(d = Alldevs; D; d = d->next) -     { -printf"%d.%s", ++i, d->name); -         if(d->description) -printf"(%s) \ n", d->description); in         Else -printf"(No description available) \ n"); to     } +  -     if(i = =0) the     { *printf"\nno Interfaces found! Make sure WinPcap is installed.\n"); $         return-1;Panax Notoginseng     } -  theprintf"Enter The interface number (1-%d):", i); +scanf"%d", &inum); A  the     if(Inum <1|| Inum >i) +     { -printf"\ninterface number out of range.\n"); $         /*Release Device List*/ $ Pcap_freealldevs (Alldevs); -         return-1; -     } the  -     /*jump to the selected adapter*/Wuyi      for(d = alldevs, I =0; I < inum-1; D = D->next, i++); the  -     /*turn on the device*/ Wu     if(Adhandle = Pcap_open (D->name,//Device Name -         65536,//65535 guaranteed to capture the full contents of each packet on different data link layers AboutPcap_openflag_promiscuous,//Promiscuous Mode $          +,//read time-out period -Null//Remote machine Verification -Errbuf//Error Buffer Pool -)) ==NULL) A     { +fprintf (stderr,"\nunable to open the adapter.%s are not supported by winpcap\n", d->name); the         /*Release Device List*/ - Pcap_freealldevs (Alldevs); $         return-1; the     } the  theprintf"\nlistening on%s...\n", d->description); the  -     /*Release Device List*/ in Pcap_freealldevs (Alldevs); the  the     /*Start Capturing*/ AboutPcap_loop (Adhandle,0, Packet_handler, NULL); the  the     return 0; the } +  -  the /*each time a packet is captured, Libpcap automatically calls this callback function*/Bayi voidPacket_handler (U_char *param,Const structPcap_pkthdr *header,ConstU_char *pkt_data) the { the     structTM *Ltime; -     Chartimestr[ -]; - time_t local_tv_sec; the  the     /*convert timestamps to recognizable formats*/ theLocal_tv_sec = header->ts.tv_sec; theLtime = localtime (&local_tv_sec); -Strftime (TIMESTR,sizeofTIMESTR,"%h:%m:%s", ltime); the  theprintf"%s,%.6d len:%d\n", Timestr, Header->ts.tv_usec, header->len); the 94}

When the adapter is opened, the capture can be done with pcap_dispatch () or Pcap_loop (). The two functions are very similar, except that PCAP_ dispatch () returns (although not guaranteed) when the time-out is reached (timeout expires), and Pcap_loop () does not return, only if the CNT packet is captured, so Pcap_loop () will block the use of the network for a short period of time. Pcap_loop () for our simple example, the Pcap_dispatch () function is typically used in more complex programs.

Both functions have a callback parameter, Packet_handler points to a function that can receive packets. This function is called by LIBPCAP when each new packet is received and a common state is received (similar to the user parameter in function Pcap_loop () and Pcap_dispatch (), and the header of the packet is usually some such as a timestamp, Packet length information, as well as the actual data containing the protocol header. Note: The redundant checksum CRC is no longer supported because the adapter will remove the CRC when the frame arrives at the adapter and is validated, while most adapters will discard the CRC error packets directly, so WinPcap cannot capture them.

The above program parses the timestamp and length of each packet from the header of the PCAP_PKTHDR and prints it on the screen.

Note that using the Pcap_loop () function may encounter obstacles, primarily because it is called directly by the packet capture driver. Therefore, the user program is not directly controlled by it. Another implementation method (also a way to improve readability) is to use the PCAP_NEXT_EX () function. For the use of this function, we will show you in the next lecture. (No callback method is used to capture the packet).

WinPcap Note 3 Open the adapter and capture the packet

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.