我最近在学习使用libpcap库函数,它是网络中使用最多的一种抓报库函数。下面是对其基本的应用实例:
#include <stdio.h>
#include <stdlib.h>#include <pcap.h>
#include <arpa/inet.h>
#include <errno.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/if_ether.h>
#include <linux/ip.h>
#include <linux/tcp.h>
#include <string.h>
struct arp_header
{
u_int16_t arp_hardware_type; /*硬件类型 */
u_int16_t arp_protocol_type; /*协议类型 */
u_int8_t arp_hardware_length; /*硬件地址长度 */
u_int8_t arp_protocol_length; /*协议地址长度 */
u_int16_t arp_operation_code; /*ARP操作码 */
u_int8_t arp_source_ethernet_address[6]; /*源以太网地址 */
u_int8_t arp_source_ip_address[4]; /*源IP地址 */
u_int8_t arp_destination_ethernet_address[6]; /*目的以太网地址 */
u_int8_t arp_destination_ip_address[4]; /*目的IP地址 */
};
/*ip协议格式的定义*/
struct ip_header
{
#ifdef WORDS_BIGENDIAN
u_int8_t ip_version:4, ip_header_length:4;
#else
u_int8_t ip_header_length:4, ip_version:4;
#endif
u_int8_t ip_tos; //服务质量
u_int16_t ip_length; //总长度
u_int16_t ip_id; //标识
u_int16_t ip_off; //偏移
u_int8_t ip_ttl; //生存时间
u_int8_t ip_protocol; //协议类型
u_int16_t ip_checksum; //校验和
struct in_addr ip_souce_address; //源ip地址
struct in_addr ip_destination_address; //目的ip地址
};
/*tcp协议格式的定义*/
struct tcp_header
{
#ifdef WORDS_BIGENDIAN
u_int8_t tcp_offset:4, tcp_reserved:4;
#else
u_int8_t tcp_reserved:4, tcp_offset:4;
#endif
u_int16_t tcp_source_port; //源端口号
u_int16_t tcp_destination_port; //目的端口号
u_int32_t tcp_acknowledgement; //序列号
u_int32_t tcp_ack; //确认号
u_int8_t tcp_flags; //标记
u_int16_t tcp_windows; //窗口大小
u_int16_t tcp_checksum; //校验和
u_int16_t tcp_urgent_pointer; //紧急指针
};
/*udp些一个是的定义*/
struct udp_header
{
u_int16_t udp_source_port; /*源端口号 */
u_int16_t udp_destination_port; /*目的端口号 */
u_int16_t udp_length; /*长度 */
u_int16_t udp_checksum; /*校验和 */
};
/*icmp协议格式的定义*/
struct icmp_header
{
u_int8_t icmp_type; /*ICMP类型 */
u_int8_t icmp_code; /*ICMP代码 */
u_int16_t icmp_checksum; /*校验和 */
u_int16_t icmp_id; /*标识 */
u_int16_t icmp_sequence; /*序列号 */
};
/*分析tcp协议的回调函数*/
void
tcp_protocol_callback (u_char * argument,
const struct pcap_pkthdr *packet_header,
const u_char * packet_content)
{
struct tcp_header *tcp_protocol;
u_char flags;
u_int header_len;
u_short source_port;
u_short destination_port;
u_short windows;
u_short urgent_pointer;
u_int sequence;
u_int acknowledgement;
u_int16_t checksum;
tcp_protocol = (struct tcp_header *) (packet_content + 14 + 20);
source_port = ntohs (tcp_protocol->tcp_source_port);
destina