#include <stdio.h> #include <errno.h> #include <sys/ioctl.h> #include <stdlib.h> #include <sys/socket.h> #include <sys/types.h> #include <string.h> #include <linux/ip.h> #include <linux/in.h> #include <linux/if_ether.h> #include <unistd.h> #include <net/if.h> int main(int argc, char **argv) { int sock, n, i; char buffer[2048]; struct ethhdr *eth; struct iphdr *iph; struct ifreq ethreq; //创建原始套接字 if((sock=socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL)))<0) { perror("socket"); exit(1); } /* 将网卡设为混杂模式,其中"eno16777736"为网络设备名称 */ strncpy(ethreq.ifr_name,"eno16777736",IFNAMSIZ); if (ioctl(sock,SIOCGIFFLAGS,ðreq)==-1) { perror("ioctl"); close(sock); exit(1); } ethreq.ifr_flags|=IFF_PROMISC; if (ioctl(sock,SIOCSIFFLAGS,ðreq<span id="transmark"></span>)==-1) { perror("ioctl"); close(sock); exit(1); } /* 获取经过网络设备的所有数据包,并提取MAC的目的地址和源地址 */ while(1) { printf("============================================================================================================== <span id="transmark"></span>================= "); i += n = recvfrom(sock, buffer, 2048, 0, NULL, NULL); printf("%d bytes read ", n); eth = (struct ethhdr*)buffer; printf("Dest MAC addr:%02x:%02x:%02x:%02x:%02x:%02x ", eth->h_dest[0], eth->h_dest[1], eth->h_dest[2], eth->h_dest[3] , eth->h_dest[4],eth->h_dest[5]); printf("Source MAC addr:%02x:%02x:%02x:%02x:%02x:%02x ",eth->h_source[0],eth->h_source[1],eth->h_source[2],eth->h_sou rce[3],eth->h_source[4],eth->h_source[5]); } return 0; }