pcap学习
- #include <pcap.h>
- char errbuf[PCAP_ERRBUF_SIZE];
- pcap_t *pcap_open_live(const char *device, int snaplen,int promisc, int to_ms, char *errbuf)
- pcap_t *pcap_open_dead(int linktype, int snaplen)
- pcap_t *pcap_open_offline(const char *fname, char *errbuf)
- pcap_dumper_t *pcap_dump_open(pcap_t *p, const char *fname)
- int pcap_setnonblock(pcap_t *p, int nonblock, char *errbuf);
- int pcap_getnonblock(pcap_t *p, char *errbuf);
- int pcap_findalldevs(pcap_if_t **alldevsp, char *errbuf)
- void pcap_freealldevs(pcap_if_t *alldevs)
- char *pcap_lookupdev(char *errbuf)
- int pcap_lookupnet(const char *device, bpf_u_int32 *netp,bpf_u_int32 *maskp, char *errbuf)
- int pcap_dispatch(pcap_t *p, int cnt,pcap_handler callback, u_char *user)
- int pcap_loop(pcap_t *p, int cnt,pcap_handler callback, u_char *user)
- void pcap_dump(u_char *user, struct pcap_pkthdr *h,u_char *sp)
- int pcap_compile(pcap_t *p, struct bpf_program *fp, char *str, int optimize, bpf_u_int32 netmask)
- int pcap_setfilter(pcap_t *p, struct bpf_program *fp)
- void pcap_freecode(struct bpf_program *);
- const u_char *pcap_next(pcap_t *p, struct pcap_pkthdr *h)
- int pcap_next_ex(pcap_t *p, struct pcap_pkthdr **pkt_header, const u_char **pkt_data)
- void pcap_breakloop(pcap_t *)
- int pcap_datalink(pcap_t *p)
- int pcap_list_datalinks(pcap_t *p, int **dlt_buf);
- int pcap_set_datalink(pcap_t *p, int dlt);
- int pcap_datalink_name_to_val(const char *name);
- const char *pcap_datalink_val_to_name(int dlt);
- const char *pcap_datalink_val_to_description(int dlt);
- int pcap_snapshot(pcap_t *p)
- int pcap_is_swapped(pcap_t *p)
- int pcap_major_version(pcap_t *p)
- int pcap_minor_version(pcap_t *p)
- int pcap_stats(pcap_t *p, struct pcap_stat *ps)
- FILE *pcap_file(pcap_t *p)
- int pcap_fileno(pcap_t *p)
- void pcap_perror(pcap_t *p, char *prefix)
- char *pcap_geterr(pcap_t *p)
- char *pcap_strerror(int error)
- const char *pcap_lib_version(void)
- void pcap_close(pcap_t *p)
- int pcap_dump_flush(pcap_dumper_t *p)
- FILE *pcap_dump_file(pcap_dumper_t *p)
- void pcap_dump_close(pcap_dumper_t *p)
DESCRIPTION
The Packet Capture libraryprovides a high level interface to packet capture systems. All packetson the network, even those destined for other hosts, are accessiblethrough this mechanism.
ROUTINES
NOTE:errbuf inpcap_open_live(),pcap_open_dead(),pcap_open_offline(),pcap_setnonblock(),pcap_getnonblock(),pcap_findalldevs(),pcap_lookupdev(),andpcap_lookupnet()is assumed to be able to hold at least PCAP_ERRBUF_SIZEchars.
pcap_open_live()is used toobtain a packet capture descriptor to look at packets on the network.deviceis a string that specifies the network device to open; on Linux systems with 2.2 or later kernels, a device argument of "any" or NULL can be used to capture packets from all interfaces.snaplenspecifies the maximum number of bytes to capture. If this value is less than the size of a packet that is captured, only the first snaplen bytes of that packet will be captured and provided as packet data. A value of 65535 should be sufficient足够的, on most if not all networks, to capture all the data available from the packet.promiscspecifies if the interface is to be put into promiscuous混杂 mode.(Note that even if this parameter is false, the interface could well be in promiscuous mode for some other reason.)
For now, this doesn't work on the "any" device; if an argument of "any" or NULL is supplied, thepromisc flag is ignored.to_msspecifies the read timeout in milliseconds. The read timeout is used to arrange that the read not necessarily return immediately when a packet is seen, but that it wait for some amount of time to allow more packets to arrive and to read multiple packets from the OS kernel in one operation. Not all platforms support a read timeout; on platforms that don't, the read timeout is ignored. A zero value forto_ms, on platforms that support a read timeout,will cause a read to wait forever to allow enough packets to arrive, with no timeout.errbufis used to return error or warning text. It will be set to error text when pcap_open_live()fails and returnsNULL.errbufmay also be set to warning text when pcap_open_live() succeds; to detect this case the caller should store a zero-length string inerrbuf before calling pcap_open_live() and display the warning to the user if errbuf is no longer a zero-length string.
pcap_open_dead()is used for creating a pcap_t structure to use when calling the other functions in libpcap. It is typically used when just using libpcap for compiling BPF code.
pcap_open_offline() is called toopen a ``savefile'' for reading.fname specifies the name of the file to open. The file has the same format as those used bytcpdump(1) andtcpslice(1).The name "-" in a synonym for stdin.errbuf is used to return error text and is only set when pcap_open_offline() fails and returns NULL.
pcap_dump_open() is called to open a ``savefile'' for writing. The name "-" in a synonymfor stdout. NULLis returned on failure.pis a pcap struct as returned by pcap_open_offline() or pcap_open_live().fname specifies the name of the file to open.If NULLis returned, pcap_geterr() can be used to get the error text.
pcap_setnonblock() puts a capture descriptor, opened with pcap_open_live(),into ``non-blocking'' mode, or takes it out of ``non-blocking'' mode,depending on whether the nonblockargument is non-zero or zero. It has no effect on ``savefiles''.If there is an error, -1 is returned anderrbuf is filled in with an appropriate error message; otherwise, 0 isreturned.In ``non-blocking'' mode, an attempt to read from the capture descriptor withpcap_dispatch()will, if no packets are currently available to be read, return 0 immediately rather than blocking waiting for packets to arrive.pcap_loop()andpcap_next()will not work in ``non-blocking'' mode.
pcap_getnonblock() returns the current ``non-blocking'' state of the capture descriptor; it always returns 0 on ``savefiles''.If there is an error, -1 is returned anderrbuf is filled in with an appropriate error message.
pcap_findalldevs() constructs a list of network devices that can be opened withpcap_open_live().(Note that there may be network devices that cannot be opened withpcap_open_live() by theprocess calling pcap_findalldevs(),because, for example, that process might not have sufficient privileges没有足够的权限 to open them for capturing; if so, those devices will not appear on thelist.)
all devsp is set to point to the first element of the list; each element of thelist is of type pcap_if_t,and has the following members:
-
- next
- if not NULL,a pointer to the next element in the list;NULLfor the last element of the list
- name
- a pointer to a string giving a name for the device to pass topcap_open_live()
- description
- if notNULL,a pointer to a string giving a human-readable description of the device
- addresses
- a pointer to the first element of a list of addresses for the interface
- flags
- interface flags:
-
- PCAP_IF_LOOPBACK
- set if the interface is a loopback interface
-
Each element of the list of addresses is of typepcap_addr_t,and has the following members:
-
- next
- if not NULL,a pointer to the next element in the list;NULLfor the last element of the list
- addr
- a pointer to astruct sockaddrcontaining an address
- netmask
- if not NULL,a pointer to astruct sockaddrthat contains the netmask corresponding to the address pointed to byaddr
- broadaddr
- if not NULL,a pointer to astruct sockaddrthat contains the broadcast address corresponding to the address pointedto byaddr;may be null if the interface doesn't support broadcasts
- dstaddr
- if not NULL,a pointer to astruct sockaddrthat contains the destination address corresponding to the address pointedto byaddr;may be null if the interface isn't a point-to-point interface
-1is returned on failure, in which caseerrbufis filled in with an appropriate error message;0is returned on success.
pcap_freealldevs()is used to free a list allocated by pcap_findalldevs().
pcap_lookupdev()returns a pointer to a network device suitable for use with pcap_open_live() and pcap_lookupnet().If there is an error,NULLis returned anderrbufis filled in with an appropriate error message.
pcap_lookupnet()is used todetermine the network number andmask associated with the network device device.Bothnetpandmaskp are bpf_u_int32 pointers. A return of -1 indicates an error in which caseerrbufis filled in with an appropriate error message.
pcap_dispatch() is used to collect and process packets.cnt specifies the maximum number of packets to process before returning.This is not a minimum number; when reading a live capture, only one bufferful of packets is read at a time, so fewer thancntpackets may be processed. A cntof -1 processes all the packets received in one buffer when reading alive capture, or all the packets in the file when reading a``savefile''.callbackspecifies a routine to be called with three arguments:a u_char pointer which is passed in from pcap_dispatch(), a const structpcap_pkthdr pointer to a structure with the following members:
-
- ts
- a struct timeval containing the time when the packet was captured
- caplen
- a bpf_u_int32 giving the number of bytes of the packet that are available from thecapture
- len
-
a bpf_u_int32 giving the length of the packet, in bytes (which might be more than the number of bytes available from the capture, if the length of the packet is larger than the maximum number of bytes to capture)
and a const u_char pointer to the first caplen(as given in the struct pcap_pkthdra pointer to which is passed to the callback routine) bytes of data from the packet (which won't necessarily be the entire packet; to capture the entire packet, you will have to provide a value forsnaplen in your call to pcap_open_live()that is sufficiently large to get all of the packet's data - a value of 65535 should be sufficient on most if not all networks).
The number of packets read is returned.0 is returned if no packets were read from a live capture (if, forexample, they were discarded because they didn't pass the packet filter,or if, on platforms that support a read timeout that starts before anypackets arrive, the timeout expires before any packets arrive, or if thefile descriptor for the capture device is in non-blocking mode and nopackets were available to be read) or if no more packets are availablein a ``savefile.'' A return of -1 indicatesan error in which case pcap_perror()or pcap_geterr() may be used to display the error text. A return of -2 indicates that the loop terminated due to a call topcap_breakloop() before any packets were processed.If your application uses pcap_breakloop(),make sure that you explicitly check for -1 and -2, rather than justchecking for a return value < 0.
NOTE:when reading a live capture,pcap_dispatch()will not necessarily return when the read times out; on some platforms,the read timeout isn't supported, and, on other platforms, the timerdoesn't start until at least one packet arrives. This means that theread timeout shouldNOTbe used in, for example, an interactive application, to allow the packetcapture loop to ``poll'' for user input periodically, as there's noguarantee thatpcap_dispatch()will return after the timeout expires.
pcap_loop() is similar to pcap_dispatch() except it keeps reading packets untilcnt packets are processed or an error occurs.It doesnot return when live read timeouts occur.Rather, specifying a non-zero read timeout to pcap_open_live() and then callingpcap_dispatch() allows the reception and processing of any packets that arrive when the timeout occurs.A negative cntcausespcap_loop() to loop forever (or at least until an error occurs). -1 is returned onan error; 0 is returned if cntis exhausted; -2 is returned if the loop terminated due to a call topcap_breakloop() before any packets were processed.If your application uses pcap_breakloop(),make sure that you explicitly check for -1 and -2, rather than justchecking for a return value < 0.
pcap_next() reads the next packet (by callingpcap_dispatch() with acntof 1) and returns a u_char pointer to the data in that packet. (Thepcap_pkthdr struct for that packet is not supplied.) NULLis returned if an error occured, or if no packets were read from a live capture (if, for example, they were discarded because they didn't passthe packet filter, or if, on platforms that support a read timeout that starts before any packets arrive, the timeout expires before any packets arrive, or if the file descriptor for the capture device is innon-blocking mode and no packets were available to be read), or if no more packets are available in a ``savefile.'' Unfortunately, there is no way to determine whether an error occured or not.
pcap_next_ex()reads the next packet and returns a success/failure indication:
-
- 1
- the packet was read without problems
- 0
- packets are being read from a live capture, and the timeout expired
- -1
- an error occurred while reading the packet
- -2
- packets are being read from a ``savefile'', and there are no morepackets to read from the savefile.
If the packet was read without problems, the pointer pointed to by thepkt_header argument is set to point to the pcap_pkthdrstruct for the packet, and the pointer pointed to by thepkt_data argument is set to point to the data in the packet.
pcap_breakloop()sets a flag that willforce pcap_dispatch() or pcap_loop() to return rather than looping; they will return the number of packets that have been processed so far, or -2 if no packets have beenprocessed so far.
This routine is safe to use inside a signal handler on UNIX or a console control handler on Windows, as it merely sets a flag that is checked within the loop.
The flag is checked in loops reading packets from the OS - a signal by itself will not necessarily terminate those loops - as well as in loopsprocessing a set of packets returned by the OS. Note that if you are catching signals on UNIX systems that support restarting system calls after a signal, and calling pcap_breakloop() in the signal handler, you must specify, when catching those signals,that system calls should NOT be restarted by that signal. Otherwise, if the signal interrupted a call reading packets in a live capture,when your signal handler returns after calling pcap_breakloop(), the call will be restarted, and the loop will not terminate until more packets arrive and the call completes.
Note that pcap_next() will, on some platforms, loop reading packets from the OS; that loop will not necessarily be terminated by a signal, sopcap_breakloop() should be used to terminate packet processing even if pcap_next()is being used.
pcap_breakloop() does not guarantee that no further packets will be processed by pcap_dispatch() orpcap_loop() after it is called; at most one more packet might be processed.
If -2 is returned from pcap_dispatch() or pcap_loop(),the flag is cleared, so a subsequent call will resume reading packets. If a positive number is returned, the flag is not cleared, so asubsequent call will return -2 and clear the flag.
pcap_dump() outputs a packet to the ``savefile'' opened withpcap_dump_open(). Note that its calling arguments are suitable for use with pcap_dispatch() orpcap_loop().If called directly, the user parameter is of typepcap_dumper_t as returned bypcap_dump_open().
pcap_compile() is used to compile the stringstr into a filter program.programis a pointer to a bpf_program struct and is filled in bypcap_compile().optimizecontrols whether optimization on the resulting code is performed.netmaskspecifies the IPv4 netmask of the network on which packets are being captured; it is used only when checking for IPv4 broadcast addresses in the filter program. If the netmask of the network on which packets are being captured isn't known to the program, or if packets are being captured on the Linux "any" pseudo-interface that can capture on more than one network, a value of 0 can be supplied; tests for IPv4 broadcast addreses won't be done correctly, but all other tests in the filter program will be OK. A return of -1 indicates an error in which casepcap_geterr() may be used to display the error text.
pcap_compile_nopcap() is similar to pcap_compile() except that instead of passing a pcap structure, one passes the snaplen and linktype explicitly. It is intended to be used for compiling filters for direct BPF usage, without necessarily havingcalledpcap_open().A return of -1 indicates an error; the error text is unavailable.(pcap_compile_nopcap()is a wrapper aroundpcap_open_dead(),pcap_compile(),and pcap_close();the latter three routines can be used directly in order to get the error text for a compilation error.)
pcap_setfilter()is used to specify a filter program.fpis a pointer to a bpf_program struct, usually the result of a call topcap_compile().-1 is returned on failure, in which case pcap_geterr() may be used to display the error text;0 is returned on success.
pcap_freecode() is used to free up allocated memory pointed to by abpf_program struct generated by pcap_compile() when that BPF program is no longer needed, for example after it has been made the filter program for a pcap structure by a call topcap_setfilter().
pcap_datalink()returns the link layer type; link layer types it can return include:
-
- DLT_NULL
- BSD loopback encapsulation; the link layer header is a 4-byte field, in host byte order, containing a PF_ value from socket.h for the network-layer protocol of the packet.
- Note that ``host byte order'' is the byte order of the machine on which the packets are captured, and the PF_ values are for the OS of themachine on which the packets are captured; if a live capture is beingdone, ``host byte order'' is the byte order of the machine capturing thepackets, and the PF_ values are those of the OS of the machine capturingthe packets, but if a ``savefile'' is being read, the byte order and PF_values arenotnecessarily those of the machine reading the capture file.
- DLT_EN10MB
- Ethernet (10Mb, 100Mb, 1000Mb, and up)
- DLT_IEEE802
- IEEE 802.5 Token Ring
- DLT_ARCNET
- ARCNET
- DLT_SLIP
- SLIP; the link layer header contains, in order:
-
a 1-byte flag, which is 0 for packets received by the machine and 1 forpackets sent by the machine;
a 1-byte field, the upper 4 bits of which indicate the type of packet,as per RFC 1144:
-
- 0x40
- an unmodified IP datagram (TYPE_IP);
- 0x70
- an uncompressed-TCP IP datagram (UNCOMPRESSED_TCP), with that byte beingthe first byte of the raw IP header on the wire, containing theconnection number in the protocol field;
- 0x80
- a compressed-TCP IP datagram (COMPRESSED_TCP), with that byte being thefirst byte of the compressed TCP/IP datagram header;
for UNCOMPRESSED_TCP, the rest of the modified IP header, and forCOMPRESSED_TCP, the compressed TCP/IP datagram header;
-
-
for a total of 16 bytes; the uncompressed IP datagram follows the header.
-
- DLT_PPP
- PPP; if the first 2 bytes are 0xff and 0x03, it's PPP in HDLC-likeframing, with the PPP header following those two bytes, otherwise it'sPPP without framing, and the packet begins with the PPP header.
- DLT_FDDI
- FDDI
- DLT_ATM_RFC1483
- RFC 1483 LLC/SNAP-encapsulated ATM; the packet begins with an IEEE 802.2LLC header.
- DLT_RAW
- raw IP; the packet begins with an IP header.
- DLT_PPP_SERIAL
- PPP in HDLC-like framing, as per RFC 1662, or Cisco PPP with HDLCframing, as per section 4.3.1 of RFC 1547; the first byte will be 0xFFfor PPP in HDLC-like framing, and will be 0x0F or 0x8F for Cisco PPPwith HDLC framing.
- DLT_PPP_ETHER
- PPPoE; the packet begins with a PPPoE header, as per RFC 2516.
- DLT_C_HDLC
- Cisco PPP with HDLC framing, as per section 4.3.1 of RFC 1547.
- DLT_IEEE802_11
- IEEE 802.11 wireless LAN
- DLT_FRELAY
- Frame Relay
- DLT_LOOP
- OpenBSD loopback encapsulation; the link layer header is a 4-byte field, innetworkbyte order, containing a PF_ value from OpenBSD'ssocket.hfor the network-layer protocol of the packet.
- Note that, if a ``savefile'' is being read, those PF_ values arenotnecessarily those of the machine reading the capture file.
- DLT_LINUX_SLL
- Linux "cooked" capture encapsulation; the link layer header contains, inorder:
-
a 2-byte "packet type", in network byte order, which is one of:
-
- 0
- packet was sent to us by somebody else
- 1
- packet was broadcast by somebody else
- 2
- packet was multicast, but not broadcast, by somebody else
- 3
- packet was sent by somebody else to somebody else
- 4
- packet was sent by us
a 2-byte field, in network byte order, containing a Linux ARPHRD_ valuefor the link layer device type;
a 2-byte field, in network byte order, containing the length of thelink layer address of the sender of the packet (which could be 0);
an 8-byte field containing that number of bytes of the link layer header(if there are more than 8 bytes, only the first 8 are present);
a 2-byte field containing an Ethernet protocol type, in network byteorder, or containing 1 for Novell 802.3 frames without an 802.2 LLCheader or 4 for frames beginning with an 802.2 LLC header.
-
-
- DLT_LTALK
- Apple LocalTalk; the packet begins with an AppleTalk LLAP header.
- DLT_PFLOG
- OpenBSD pflog; the link layer header contains, in order:
-
a 4-byte PF_ value, in network byte order;
a 16-character interface name;
a 2-byte rule number, in network byte order;
a 2-byte reason code, in network byte order, which is one of:
-
- 0
- match
- 1
- bad offset
- 2
- fragment
- 3
- short
- 4
- normalize
- memory
a 2-byte action code, in network byte order, which is one of:
-
- 0
- passed
- 1
- dropped
- 2
- scrubbed
a 2-byte direction, in network byte order, which is one of:
-
- 0
- incoming or outgoing
- 1
- incoming
- 2
- outgoing
-
-
- DLT_PRISM_HEADER
- Prism monitor mode information followed by an 802.11 header.
- DLT_IP_OVER_FC
- RFC 2625 IP-over-Fibre Channel, with the link-layer header being theNetwork_Header as described in that RFC.
- DLT_SUNATM
- SunATM devices; the link layer header contains, in order:
-
a 1-byte flag field, containing a direction flag in the uppermost bit,which is set for packets transmitted by the machine and clear forpackets received by the machine, and a 4-byte traffic type in thelow-order 4 bits, which is one of:
-
- 0
- raw traffic
- 1
- LANE traffic
- 2
- LLC-encapsulated traffic
- 3
- MARS traffic
- 4
- IFMP traffic
- 5
- ILMI traffic
- 6
- Q.2931 traffic
a 1-byte VPI value;
a 2-byte VCI field, in network byte order.
-
-
- DLT_IEEE802_11_RADIO
- link-layer information followed by an 802.11 header - seehttp://www.shaftnet.org/~pizza/software/capturefrm.txt for a descriptionof the link-layer information.
- DLT_ARCNET_LINUX
- ARCNET, with no exception frames, reassembled packets rather than rawframes, and an extra 16-bit offset field between the destination hostand type bytes.
- DLT_LINUX_IRDA
- Linux-IrDA packets, with aDLT_LINUX_SLLheader followed by the IrLAP header.
pcap_list_datalinks() is used to get a list of the supported data link types of the interface associated with the pcap descriptor.pcap_list_datalinks()allocates an array to hold the list and sets *dlt_buf. The caller is responsible for freeing the array.-1 is returned on failure; otherwise, the number of data link types in the array is returned.
pcap_set_datalink() is used to set the current data link type of the pcap descriptor to the type specified bydlt. -1 is returned on failure.
pcap_datalink_name_to_val() translates a data link type name, which is aDLT_ name with theDLT_ removed, to the corresponding data link type value. The translation is case-insensitive.-1 is returned on failure.
pcap_datalink_val_to_name() translates a data link type value to the corresponding data link typename. NULL is returned on failure.
pcap_datalink_val_to_description() translates a data link type value to a short description of that datalink type.NULL is returned on failure.
pcap_snapshot() returns the snapshot length specified when pcap_open_live() was called.
pcap_is_swapped() returns true if the current ``savefile'' uses a different byte order than the current system.
pcap_major_version() returns the major number of the file format of the savefile;pcap_minor_version() returns the minor number of the file format of the savefile. The version number is stored in the header of the savefile.
pcap_file() returns the standard I/O stream of the ``savefile,'' if a ``savefile'' was opened with pcap_open_offline(),or NULL, if a network device was opened with pcap_open_live().
pcap_stats() returns 0 and fills in a pcap_stat struct. The values represent packet statistics from the start of therun to the time of the call. If there is an error or the underlying packet capture doesn't support packet statistics, -1 is returned andthe error text can be obtained with pcap_perror() orpcap_geterr().pcap_stats() is supported only on live captures, not on ``savefiles''; no statistics are stored in ``savefiles'', so no statistics are available when reading from a ``savefile''.
pcap_fileno() returns the file descriptor number from which captured packets are read,if a network device was opened withpcap_open_live(),or -1, if a ``savefile'' was opened with pcap_open_offline().
pcap_perror() prints the text of the last pcap library error onstderr,prefixed by prefix.
pcap_geterr()returns the error text pertaining to the last pcap library error.NOTE:the pointer it returns will no longer point to a valid error messages tring after the pcap_t passed to it is closed; you must use or copy the string before closing the pcap_t.
pcap_strerror() is provided in casestrerror(1) isn't available.
pcap_lib_version() returns a pointer to a string giving information about the version ofthe libpcap library being used; note that it contains more informationthan just a version number.
pcap_close() closes the files associated with pand deallocates resources.
pcap_dump_file()returns the standard I/O stream of the ``savefile'' opened bypcap_dump_open().
pcap_dump_flush() flushes the output buffer to the ``savefile,'' so that any packets written withpcap_dump() but not yet written to the ``savefile'' will be written.-1is returned on error, 0 on success.
pcap_dump_close() closes the ``savefile.''
www.tcpdump.org
一)
数据结构
•1) typedef struct _ADAPTER ADAPTER //描述一个网络适配器;
•2) typedef struct _PACKETPACKET //描述一组网络数据报的结构;
•3) typedef struct NetTypeNetType //描述网络类型的数据结构;
•4) typedef struct npf_if_addr npf_if_addr //描述一个网络适配器的ip地址;
•5) struct bpf_hdr //数据报头部;
•6) struct bpf_stat //当前捕获数据报的统计信息。
函数
1)int pcap_findalldevs ( pcap_if_t **alldevsp, char * errbuf)
功能:列出当前所有可用的网络设备(网卡)
所在头文件:pcap.h
参数说明: pcap_if_t ** alldevsp 指向pcap_if_t结构列表的指针的地址。实际使用时,声明一个pcap_if_t结构的指针(pcap_if_t *alldevsp),然后把该地址作为参数传入即可(&alldevsp)。
char * errbuf 错误缓冲区,要求长度至少为PCAP_ERRBUF_SIZE字节
返回值: -1:出错,将会向错误缓冲中填充错误信息,错误信息为ASCII码,可以直接打印出来。
0:正确返回,可以使用alldevsp访问所有网络硬件
pcap_if的结构
Struct pcap_if {
structpcap_if *next;
char *name;
chat *description;
struct pcap_addraddress;
u_int flags;
}
也可以用pcap_if_t 代替pcap_if
2)pcap_t * pcap_open_live ( char * device, int snaplen, int promisc,int to_ms, char * errbuf );
获取一个包捕捉句柄,类似文件操作函数使用的文件句柄。
device指定网络接口设备名。
snaplen指定单包最大捕捉字节数。
promisc指定网络接口进入混杂模式。
to_ms指定毫秒级读超时,0可能代表永不超时。
errbuf包含失败原因。
如果调用失败返回NULL
3)void pcap_close ( pcap_t *p )
该函数用于关闭pcap_open_live()获取的包捕捉句柄,释放相关资源。
4int pcap_lookupnet ( char * device, bpf_u_int32 * netp, pf_u_int32 * maskp, char * errbuf );
该函数用于获取指定网络接口的IP地址、子网掩码。
5)int pcap_compile ( pcap_t * p, struct bpf_program * fp, char * str,int optimize
, bpf_u_int32 netmask );
该函数用于解析过滤规则串,填写bpf_program结构。str指向过滤规则串。
6)int pcap_setfilter ( pcap_t * p, struct bpf_program * fp );
该函数用于设置pcap_compile()解析完毕的过滤规则,完全可以自己提供过滤规则,无须pcap_compile()介入
7) int pcap_dispatch ( pcap_t * p, int cnt, pcap_handler callback,
u_char * user );
捕捉报文以及分发报文到预先指定好的处理函数(回调函数)。
pcap_dispatch()接收够cnt个报文便返回,如果cnt为-1意味着所有报文集中在一个缓冲区中。如果cnt为0,仅当发生错误、读取到EOF或者读超时到了(pcap_open_live中指定)才停止捕捉报文并返回。
8)int pcap_loop(pcap_t *p, int cnt, pcap_handler callback, u_char*user);
这里pcap_loop的作用是抓包,每抓到一个包之后就调用callback函数来处理之,callback需要你自己编写,callback的类似于这种:
void PacketCallback(u_char *user, const struct pcap_pkthdr *h,const u_char *p);
你给出的代码是定义了一个函数指针grinder_t的类型,就可以用grinder_t来声明函数指针了
grinder应该就是作为一个回调函数来处理pcap抓到的包
pcap_loop和callback之间参数存在联系,pcap_loop的最后一个参数user是留给用户使用的,当callback被调用的时候这个值会传递给callback的第一个参数(也叫user),callback的最后一个参数p指向一块内存空间,这个空间中存放的就是pcap_loop抓到的数据包。callback的第二个参数是一个结构体指针,该结构体定义如下:
struct pcap_pkthdr {
struct timeval ts;
bpf_u_int32 caplen;
bpf_u_int32 len;
};
这个结构体是由pcap_loop自己填充的,用来取得一些关于数据包的信息
所以,在callback函数当中只有第一个user指针是可以留给用户使用的,如果你想给callback传递自己参数,那就只能通过pcap_loop的最后一个参数user来实现了
二)
在函数 pcap_open_live(), pcap_open_dead(),pcap_open_offline(), pcap_setnonblock(), pcap_getnonblock(),pcap_findalldevs(), pcap_lookupdev(), 和 pcap_lookupnet()中的errbuf假定至少有 PCAP_ERRBUF_SIZE 个字符。
typedef void(*) pcap_handler (u_char *user, const structpcap_pkthdr *pkt_header, const u_char *pkt_data)
接受数据包的回调函数的原型
pcap_t * pcap_open_live (const char *device, int snaplen, intpromisc, int to_ms, char *ebuf)
在网络中打开一个活动的捕获
pcap_t * pcap_open_dead (int linktype, int snaplen)
在还没开始捕获时,创建一个pcap_t的结构体
pcap_t * pcap_open_offline (const char *fname, char*errbuf)
打开一个 tcpdump/libpcap 格式的存储文件,来读取数据包
pcap_dumper_t * pcap_dump_open (pcap_t *p, const char*fname)
打开一个文件来写入数据包
int pcap_setnonblock (pcap_t *p, int nonblock, char*errbuf)
在阻塞和非阻塞模式间切换
int pcap_getnonblock (pcap_t *p, char *errbuf)
获得一个接口的非阻塞状态信息
int pcap_findalldevs (pcap_if_t **alldevsp, char *errbuf)
构造一个可打开的网络设备的列表 pcap_open_live()
void pcap_freealldevs (pcap_if_t *alldevsp)
释放一个接口列表,这个列表将被 pcap_findalldevs()返回
char * pcap_lookupdev (char *errbuf)
返回系统中第一个合法的设备
int pcap_lookupnet (const char *device, bpf_u_int32 *netp,bpf_u_int32 *maskp, char *errbuf)
返回接口的子网和掩码
int pcap_dispatch (pcap_t *p, int cnt, pcap_handler callback,u_char *user)
收集一组数据包
int pcap_loop (pcap_t *p, int cnt, pcap_handler callback, u_char*user)
收集一组数据包
u_char * pcap_next (pcap_t *p, struct pcap_pkthdr *h)
返回下一个可用的数据包
int pcap_next_ex (pcap_t *p, struct pcap_pkthdr **pkt_header,const u_char **pkt_data)
从一个设备接口,或从一个脱机文件中,读取一个数据包
void pcap_breakloop (pcap_t *)
设置一个标志位,这个标志位会强制 pcap_dispatch() 或 pcap_loop() 返回,而不是继续循环。
int pcap_sendpacket (pcap_t *p, u_char *buf, int size)
发送一个原始数据包
void pcap_dump (u_char *user, const struct pcap_pkthdr *h, constu_char *sp)
将数据包保存到磁盘
long pcap_dump_ftell (pcap_dumper_t *)
返回存储文件的文件位置
int pcap_compile (pcap_t *p, struct bpf_program *fp, char *str,int optimize, bpf_u_int32 netmask)
编译数据包过滤器,将程序中高级的过滤表达式,转换成能被内核级的过滤引擎所处理的东西。 (参见 过滤表达式语法)
int pcap_compile_nopcap (int snaplen_arg, int linktype_arg,struct bpf_program *program, char *buf, int optimize, bpf_u_int32mask)
在不需要打开适配器的情况下,编译数据包过滤器。这个函数能将程序中高级的过滤表达式,转换成能被内核级的过滤引擎所处理的东西。 (参见过滤表达式语法)
int pcap_setfilter (pcap_t *p, struct bpf_program *fp)
在捕获过程中绑定一个过滤器
void pcap_freecode (struct bpf_program *fp)
释放一个过滤器
int pcap_datalink (pcap_t *p)
返回适配器的链路层
int pcap_list_datalinks (pcap_t *p, int **dlt_buf)
列出数据链
int pcap_set_datalink (pcap_t *p, int dlt)
将当前pcap描述符的数据链的类型,设置成dlt给出的类型。返回-1表示设置失败。
int pcap_datalink_name_to_val (const char *name)
转换一个数据链类型的名字,即将具有DLT_remove的DLT_name,转换成符合数据链类型的值。转换是区分大小写的,返回-1表示错误。
const char * pcap_datalink_val_to_name (int dlt)
将数据链类型值转换成合适的数据链类型的名字。返回NULL表示转换失败。
const char * pcap_datalink_val_to_description (int dlt)
将数据链类型值转换成合适的数据链类型的简短的名字。返回NULL表示转换失败。
int pcap_snapshot (pcap_t *p)
返回发送给应用程序的数据包部分的大小(字节)
int pcap_is_swapped (pcap_t *p)
当前存储文件使用与当前系统不同的字节序列时,返回true
int pcap_major_version (pcap_t *p)
返回正在用来写入存储文件的pcap库的主要版本号
int pcap_minor_version (pcap_t *p)
返回正在用来写入存储文件的pcap库的次要版本号
FILE * pcap_file (pcap_t *p)
返回一个脱机捕获文件的标准流
int pcap_stats (pcap_t *p, struct pcap_stat *ps)
返回当前捕获的统计信息
void pcap_perror (pcap_t *p, char *prefix)
在标准错误输出台打印最后一次pcap库错误的文本信息,前缀是prefix。
char * pcap_geterr (pcap_t *p)
返回最后一次pcap库错误的文本信息
char * pcap_strerror (int error)
提供这个函数,以防 strerror() 不能使用。
const char * pcap_lib_version (void)
返回一个字符串,这个字符串保存着libpcap库的版本信息。注意,它除了版本号,还包含了更多的信息。
void pcap_close (pcap_t *p)
关闭一个和p关联的文件,并释放资源
FILE * pcap_dump_file (pcap_dumper_t *p)
返回一个由 pcap_dump_open()打开的存储文件的标准输入输出流
int pcap_dump_flush (pcap_dumper_t *p)
将输出缓冲写入存储文件,这样,任何使用 pcap_dump() 存储,但还没有写入文件的数据包,会被立刻写入文件。返回-1表示出错,返回0表示成功。
void pcap_dump_close (pcap_dumper_t *p)
关闭一个存储文件
Windows平台专用的扩展函数
本节中的函数是从libpcap扩展而来,为了提供更强大的功能(比如远程数据捕获,数据包缓存尺寸变化或高精度的数据包注入)。然而,目前,这些函数只能用于Windows平台。
PAirpcapHandle pcap_get_airpcap_handle (pcap_t *p)
返回一个和适配器相关联的AirPcap句柄。这个句柄可以被用来改变和CACE无线技术有关的设置。
bool pcap_offline_filter (struct bpf_program *prog, const structpcap_pkthdr *header, const u_char *pkt_data)
当给定的过滤器应用于一个脱机数据包时,返回true
int pcap_live_dump (pcap_t *p, char *filename, int maxsize, intmaxpacks)
将捕获保存到文件
int pcap_live_dump_ended (pcap_t *p, int sync)
返回内核堆处理的状态。例如,告诉我们由 pcap_live_dump() 定义的限制条件是否已经满足。
pcap_stat * pcap_stats_ex (pcap_t *p, int *pcap_stat_size)
返回当前捕获的统计信息。
int pcap_setbuff (pcap_t *p, int dim)
设置与当前适配器关联的内核缓存大小
int pcap_setmode (pcap_t *p, int mode)
将接口p的工作模式设置为mode
int pcap_setmintocopy (pcap_t *p, int size)
设置内核一次调用所受到的最小数据总数
HANDLE pcap_getevent (pcap_t *p)
返回与接口p关联的事件句柄
pcap_send_queue * pcap_sendqueue_alloc (u_int memsize)
分配一个发送队列
void pcap_sendqueue_destroy (pcap_send_queue *queue)
销毁一个发送队列
int pcap_sendqueue_queue (pcap_send_queue *queue, const structpcap_pkthdr *pkt_header, const u_char *pkt_data)
将数据包加入到发送队列
u_int pcap_sendqueue_transmit (pcap_t *p, pcap_send_queue*queue, int sync)
将一个发送队列发送至网络
int pcap_findalldevs_ex (char *source, struct pcap_rmtauth*auth, pcap_if_t **alldevs, char *errbuf)
创建一个网络设备列表,它们可以由 pcap_open()打开。
int pcap_createsrcstr (char *source, int type, const char *host,const char *port, const char *name, char *errbuf)
接收一组字符串(hotname,port,...),并根据新的格式,返回一个完整的源字符串(比如:'rpcap://1.2.3.4/eth0')
int pcap_parsesrcstr (const char *source, int *type, char *host,char *port, char *name, char *errbuf)
解析一个源字符串,并返回分离出来的内容。
pcap_t * pcap_open (const char *source, int snaplen, int flags,int read_timeout, struct pcap_rmtauth *auth, char *errbuf)
打开一个用来捕获或发送流量(仅WinPcap)的通用源。
pcap_samp * pcap_setsampling (pcap_t *p)
为数据包捕获定义一个采样方法
SOCKET pcap_remoteact_accept (const char *address, const char*port, const char *hostlist, char *connectinghost, structpcap_rmtauth *auth, char *errbuf)
阻塞,直到网络连接建立。(仅用于激活模式)
int pcap_remoteact_close (const char *host, char *errbuf)
释放一个活动连接 (仅用于激活模式).
void pcap_remoteact_cleanup
pcap学习的更多相关文章
- Python解析Pcap包类源码学习
0x1.前言 在现场取证遇到分析流量包的情况会比较少,虽然流量类设备原理是把数据都抓出来进行解析,很大一定程度上已经把人可以做的事情交给了机器自动完成. 可用于PCAP包分析的软件比如科来,W ...
- 处理 pcap 中的 mac 二进制字节流为可读格式
import struct # 利用 struct 处理字节流中的mac地址 适用于小端地址操作系统 def mac2str(bi_mac): mac = "" for i in ...
- 动手学习TCP:总结和索引
TCP是一个十分复杂的协议,通过前面几篇文章只涉及了TCP协议中一些基本的概念. 虽然说都是一些TCP最基本的概念,但是试验过程中一直在踩坑,例如:TCP flag设置错误,seq.ack号没有计算正 ...
- 动手学习TCP:TCP特殊状态
前面两篇文章介绍了TCP状态变迁,以及通过实验演示了客户端和服务端的正常状态变迁. 下面就来看看TCP状态变迁过程中的几个特殊状态. SYN_RCVD 在TCP连接建立的过程中,当服务端接收到[SYN ...
- IM通信协议逆向分析、Wireshark自定义数据包格式解析插件编程学习
相关学习资料 http://hi.baidu.com/hucyuansheng/item/bf2bfddefd1ee70ad68ed04d http://en.wikipedia.org/wiki/I ...
- 【Python】测试dpkt解析pcap
1.前言 本想借助dpkt解析mail.dns.http来辅助分析pcap包进行分析,查阅资料学习却发现并不如使用scapy那么方便. dpkt是一个python模块,可以对简单的数据包创建/解析,以 ...
- WEB安全番外第六篇--关于通过记录渗透工具的Payload来总结和学习测试用例
背景: 在WEB安全的学习过程中,了解过了原理之后,就是学习各种Payload,这里面蕴藏着丰富的知识含量,是在基本上覆盖了漏洞原理之后的进一步深入学习的必经之路.无理是Burpsuite还是Sqlm ...
- 《Linux命令学习手册》系列分享专栏
<Linux命令学习手册>系列分享专栏 <Linux命令学习手册>已整理成PDF文档,点击可直接下载至本地查阅https://www.webfalse.com/read/207 ...
- PCAP文件格式分析(做抓包软件之必备)
转载源:http://blog.csdn.net/anzijin/article/details/2008333 http://www.ebnd.cn/2009/09/07/file-format-a ...
随机推荐
- Hydra--密码破解的神器
原来不止burpsuit.sqlmap是神器,还有Hydra. 虽久闻大名,却未曾使用,今天偶然用到,发现支持的服务那真是多,ftp.ssh.smtp.imap.http...,而且支持ssl 可以想 ...
- 大型vue单页面项目优化总结
这是之前在公司oa项目优化时罗列的优化点,基本都已经完成,当时花了点心思整理的,保存在这里,方便以后其他项目用到查漏补缺. 1.打包文件中的app.js文件放入cdn,加快页面首次加载速度 2.提取公 ...
- 使用scrapy爬取金庸小说目录和章节url
刚接触使用scrapy的时候,如果一开始就想实现特别复杂的配置,显然是不太现实的,用一些小的例子可以帮助自己理解各个模块. 今天的目标:爬取http://www.luoxia.com/shendiao ...
- Dfs【bzoj3252】攻略
Description 题目简述:树版[k取方格数] 众所周知,桂木桂马是攻略之神,开启攻略之神模式后,他可以同时攻略k部游戏. 今天他得到了一款新游戏<XX半岛>,这款游戏有n个场景(s ...
- 【搜索】魔板问题(BFS)
[搜索]魔板问题 时间限制: 1 Sec 内存限制: 64 MB提交: 5 解决: 3[提交][状态][讨论版] 题目描述 据说能使持有者成为世界之主的上古神器隐藏在魔板空间,魔板由8个同样大小的 ...
- 学习LSM(Linux security module)之一:解读yama
最近打算写一个基于LSM的安全模块,发现国内现有的资料极少.因此打算自己琢磨一下.大致的学习路线如下: 由易至难使用并阅读两到三个安全模块->参照阅读模块自己实现一个安全模块->在自己实现 ...
- 设计模式-工厂模式(Factory Pattern)
本文由@呆代待殆原创,转载请注明出处. 工厂模式遵循的设计原则之一:找出代码中常变化的部分,并把这一部分分离出来.(Dependency Inversion Principle) 工厂模式简述 当我们 ...
- 【函数式权值分块】【块状链表】bzoj3065 带插入区间K小值
显然是块状链表的经典题.但是经典做法的复杂度是O(n*sqrt(n)*log^2(n))的,出题人明确说了会卡掉. 于是我们考虑每个块内记录前n个块的权值分块. 查询的时候差分什么的,复杂度就是O(n ...
- 【斜率优化】BZOJ1010 [HNOI2008]玩具装箱toy
[题目大意] P教授有编号为1...N的N件玩具,第i件玩具长度为Ci.为了方便整理,P教授要求在一个一维容器中的玩具编号是连续的.如果将第i件玩具到第j个玩具放到一 个容器中,那么容器的长度将为 x ...
- 泳池迷宫(p24)
/*2018年8月26日15:55:29作者:冰樱梦page-24泳池迷宫*/public class swiming{public static void main(String[] args){i ...