Network packet Detection
Packet Capture (sniffer): refers to the behavior of data collection on the network, which needs to be done through the NIC.
Three ways to access:
BSD Packet Filter (BPF)
SVR4 Datalink Provider Interface (DLPI)
Linux Sock_packet interface
Libpcap Library
Installation:
Apt-get Install Libpcap-dev
Common APIs
Capturing data packets
Find the default data network device to capture
The error message returned by the system is saved when the char * pcap_lookupdev (char * errbuf)//error occurs.
return value:
Returns a pointer to the device name when successful.
Failure returns null
Find the network number and subnet mask for the specified device
int pcap_lookupnet (const char * device,//pointer to device name
Bpf_u_int32 * netp,//Pointer to the acquired network number
Bpf_u_int32 * maskp,//Pointer to the obtained subnet mask
char * errbuf)//Save the error message returned by the system when an error occurs
return value:
Successfully returned 0,
The failure returns-1, and the error message is saved to the ERRBUF.
Open a network device for capturing packets
pcap_t * pcap_open_live (const char * device,//pointer to device name
int Snaplen,//length of packets captured
int promisc,//Network Interface working mode
int to_ms,//timeout when reading packets
char * errbuf)//Save system error message when error
return value:
Handle to successfully return capture packet
Failure returns null and saves error message to ERRBUF
Capturing the next frame of data
Const U_CHAR * PCAP_NEXT (pcap_t * p//pcap_open_live return handle
struct PCAP_PKTHDR * h) A structure pointer to hold the captured packet properties
return value:
Returns a pointer to a captured data frame when successful.
Failed or no data returned null.
Loop capture of multiple frame data and process
typedef void (* Pcap_handler) (U_char *user,
const struct PCAP_PKTHDR * h,const U_char *bytes);
int Pcap_loop (pcap_t * p,//pcap_open_live return handle
int cnt,//The number of data frames to capture
Pcap_handler callback,//The processing function that is executed when a frame of data is captured
U_char * user)//pass to callback parameters
See more highlights of this column: http://www.bianceng.cnhttp://www.bianceng.cn/OS/unix/