简单抓包代码(链路层)

来源:互联网 发布:旅游导航软件 编辑:程序博客网 时间:2024/05/23 13:35
#include <stdio.h>#include <stdlib.h>#include <unistd.h>#include <sys/socket.h> /*含socket函数的定义*/#include <sys/types.h>#include <sys/ioctl.h>//#include <netinet/in.h>//含struct sockaddr_in的定义,下面程序没有用到。可删#include <netinet/ip.h>/*含struct iphdr*/#include <netinet/if_ether.h>/*含struct ethhdr*/#include <net/if.h>/* 含struct ifreq 的定义。请球结构*/#define oops(msg){perror(msg);exit(0);}int main(int ac,char**av){    struct iphdr *iph;    struct ethhdr *eth;    char buffer[2048];    int sockfd;    if((sockfd=socket(AF_PACKET,SOCK_RAW,htons(ETH_P_IP)))<0)    oops("socket");    int nbytes=0;    ///////////////////////////////////////////////////    //把这段去掉,就是在普通下抓自己的包,很简单的代码,只需要    //生成一个原始套接子就可以了,然后套接子也不用绑定网卡(ip)    //它会去所有的网卡都抓过来。    /*把套接字和网卡(eth0 or any name )绑定,且把网卡设为混杂模式*/    struct ifreq ethreq;    strncpy(ethreq.ifr_name,"wlan0",IFNAMSIZ);    if((ioctl(sockfd,SIOCGIFFLAGS,ðreq))<0)    oops("io get");    ethreq.ifr_flags|=IFF_PROMISC;    if((ioctl(sockfd,SIOCSIFFLAGS,ðreq))<0)    oops("io set");    //////////////////////////////////////////////////    while(1)    {     if((nbytes=recvfrom(sockfd,buffer,sizeof(buffer),0,NULL,NULL))<0)         oops("recvfrom");     printf("recefrom %d bytes\n",nbytes);     eth=(struct ethhdr*)buffer;     int i;     printf("Mac source addr:");     for(i=0;i<6;i++)         printf("%x: ",eth->h_source[i]);     printf("\n");     printf("Mac dest addr:");     for(i=0;i<6;i++)         printf("%x: ",eth->h_dest[i]);     printf("\n");         iph=(struct iphdr*)(buffer+sizeof(struct ethhdr));     printf("ip src:%s\n",inet_ntoa(iph->saddr));     printf("ip dst:%s\n",inet_ntoa(iph->daddr));    }    return 0;}        


0 0