记得以管理者权限运行程序:
每个报文头部都有一个相应的结构体,通过这些结构体对报文进行相应的组包或拆包会方便很多。
ubuntu 12.04 中描述网络协议结构的文件如下:
以太网头部(所需要头文件:#include <net/ethernet.h>):
上面的例子,改为用结构体实现,如下:
[objc] view plaincopy在CODE上查看代码片派生到我的代码片 #include <stdio.h> #include <string.h> #include <stdlib.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <netinet/ether.h> #include <net/ethernet.h> // 以太网头部 头文件 #include <netinet/ip.h> // ip头部 头文件 // #include <net/if_arp.h> // arp头部 头文件 int main(int argc,charchar *argv[]) { int i = 0; unsigned char buf[1024] = ""; int sock_raw_fd = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL)); while(1) { unsigned char src_mac[18] = ""; unsigned char dst_mac[18] = ""; //获取链路层的数据帧 recvfrom(sock_raw_fd, buf, sizeof(buf),0,NULL,NULL); //从数据中提取mac首部信息(14个字节) struct ether_header *ethdr = NULL; ethdr = (struct ether_header *)buf; //从buf里提取目的mac、源mac sprintf(dst_mac,"%02x:%02x:%02x:%02x:%02x:%02x", ethdr->ether_dhost[0], ethdr->ether_dhost[1],ethdr->ether_dhost[2],ethdr->ether_dhost[3],ethdr->ether_dhost[4],ethdr->ether_dhost[5]); sprintf(src_mac,"%02x:%02x:%02x:%02x:%02x:%02x", ethdr->ether_shost[0], ethdr->ether_shost[1],ethdr->ether_shost[2],ethdr->ether_shost[3],ethdr->ether_shost[4],ethdr->ether_shost[5]); //判断是否为IP数据包 if( 0x0800 == ntohs(ethdr->ether_type) ) { printf("______________IP数据报_______________\n"); printf("MAC:%s >> %s\n",src_mac,dst_mac); }//0x0806为ARP数据包, 0x8035为RARP数据包 else if( 0x0806 == ntohs(ethdr->ether_type) || 0x8035 == ntohs(ethdr->ether_type) ) { printf("______________ARP数据报_______________\n"); printf("MAC:%s >> %s\n",src_mac,dst_mac); } } return 0; } |