c语言代码实现arp字段解析 详细代码
时间: 2024-02-19 14:03:18 浏览: 127
以下是使用C语言解析ARP协议包的详细代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <arpa/inet.h>
#include <netinet/if_ether.h>
#include <netinet/ip.h>
#include <netinet/ip_icmp.h>
#include <netinet/tcp.h>
#include <netinet/udp.h>
#include <netinet/in.h>
#include <net/ethernet.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>
void arp_packet_parser(const u_char *packet) {
struct ether_header *eth_header;
eth_header = (struct ether_header *) packet;
if (ntohs(eth_header->ether_type) == ETHERTYPE_ARP) {
printf("\nARP Packet:\n");
printf("Source MAC Address: %.2X:%.2X:%.2X:%.2X:%.2X:%.2X\n",
eth_header->ether_shost[0], eth_header->ether_shost[1], eth_header->ether_shost[2],
eth_header->ether_shost[3], eth_header->ether_shost[4], eth_header->ether_shost[5]);
printf("Destination MAC Address: %.2X:%.2X:%.2X:%.2X:%.2X:%.2X\n",
eth_header->ether_dhost[0], eth_header->ether_dhost[1], eth_header->ether_dhost[2],
eth_header->ether_dhost[3], eth_header->ether_dhost[4], eth_header->ether_dhost[5]);
packet += sizeof(struct ether_header);
struct ether_arp *arp_header;
arp_header = (struct ether_arp *) packet;
printf("Sender MAC Address: %.2X:%.2X:%.2X:%.2X:%.2X:%.2X\n",
arp_header->arp_sha[0], arp_header->arp_sha[1], arp_header->arp_sha[2],
arp_header->arp_sha[3], arp_header->arp_sha[4], arp_header->arp_sha[5]);
printf("Sender IP Address: %s\n", inet_ntoa(*(struct in_addr *) arp_header->arp_spa));
printf("Target MAC Address: %.2X:%.2X:%.2X:%.2X:%.2X:%.2X\n",
arp_header->arp_tha[0], arp_header->arp_tha[1], arp_header->arp_tha[2],
arp_header->arp_tha[3], arp_header->arp_tha[4], arp_header->arp_tha[5]);
printf("Target IP Address: %s\n", inet_ntoa(*(struct in_addr *) arp_header->arp_tpa));
}
}
void packet_handler(u_char *args, const struct pcap_pkthdr *header, const u_char *packet) {
arp_packet_parser(packet);
}
int main() {
char errbuf[PCAP_ERRBUF_SIZE];
pcap_t *handle;
struct bpf_program fp;
char filter_exp[] = "arp";
bpf_u_int32 net;
bpf_u_int32 mask;
// 打开网络设备
handle = pcap_open_live("eth0", BUFSIZ, 1, 1000, errbuf);
// 获取网络设备的网段和掩码
pcap_lookupnet("eth0", &net, &mask, errbuf);
// 编译过滤规则
pcap_compile(handle, &fp, filter_exp, 0, net);
// 设置过滤规则
pcap_setfilter(handle, &fp);
// 开始抓包
pcap_loop(handle, -1, packet_handler, NULL);
// 关闭网络设备
pcap_close(handle);
return 0;
}
```
以上代码使用pcap库来抓取网络数据包,并使用`arp_packet_parser()`函数来解析ARP协议包。在解析ARP协议包时,我们首先需要获取以太网帧头部,并判断是否为ARP协议包,然后再获取ARP协议包头部,从中提取出需要的信息,如MAC地址和IP地址等。最后,我们可以将这些信息打印出来,以便于查看。
阅读全文