抓原始包

      1 #include <stdio.h>
      2 #include <unistd.h>
      3 #include <sys/socket.h>
      4 #include <sys/types.h>
      5 #include <linux/if_ether.h>
      6 #include <linux/in.h>
      7 #include <stdlib.h>
      8 #define BUFFER_MAX 2048
      9
     10 int main(int argc,char *argv[])
     11 {
     12     int sock,n_read,proto;
     13     char buffer[BUFFER_MAX];
     14     char *ethhead,*iphead,*tcphead,udphead,icmphead,*p;
     15     if((sock=socket(PF_PACKET,SOCK_RAW,htons(ETH_P_IP)))<0){
     16         printf("create socket error\n");
     17         exit(0);
     18     }
     19     while(1)
     20     {
     21         n_read = recvfrom(sock,buffer,2048,0,NULL,NULL);
     22         /*
     23         14 6(dest)+6(source)+2(tpe or length)
     24         20 ip header
     25         8 icmp,tcp or udp header
     26         =42
     27         */
     28         if(n_read < 42)
     29         {
     30             printf("incomplete header, packet corrupt");
     31             continue;
     32         }
     33         ethhead = buffer;
     34         p = ethhead;
     35         int n = 0xFF;
     36         printf("MAC: %.2X:%02X:%02X:%02X:%02X:%02X==>"
     37             "%.2X:%.2X:%.2X:%.2X:%.2X:%.2X\n",
     38             p[6]&n,p[7]&n,p[8]&n,p[9]&n,p[10]&n,p[11]&n,
     39             p[0]&n,p[1]&n,p[2]&n,p[3]&n,p[4]&n,p[5]&n);
     40         iphead = ethhead + 14;
     41         p = iphead + 12;
     42         printf("IP:%d.%d.%d.%d => %d.%d.%d.%d\n",
     43         p[0]&0XFF,p[1]&0XFF,p[2]&0XFF,p[3]&0XFF,
     44         p[4]&0XFF,p[5]&0XFF,p[6]&0XFF,p[7]&0XFF);
     45         proto = (iphead + 9)[0];
     46         p = iphead + 20;
     47         printf("protocol:");
     48         switch(proto)
     49         {
     50             case IPPROTO_ICMP:
     51                 printf("ICMP\n");
     52                 break;
     53             case IPPROTO_IGMP:
     54                 printf("IGMP\n");
     55                 break;
     56             case IPPROTO_IPIP:
     57                 printf("IPIP\n");
     58                 break;
     59             case IPPROTO_TCP:
     60             case IPPROTO_UDP:
     61                 printf("%s,",proto==IPPROTO_TCP?"TCP":"UDP");
     62                 printf("source port: %u,",(p[0]<<8)&0XFF00|p[1]&0XFF);
     63                 printf("dest port:%u\n",(p[2]<<8)&0XFF00|p[3]&0XFF);
     64                 break;
     65             case IPPROTO_RAW:
     66                 printf("RAW\n");
     67                 break;
     68             default:
     69                 printf("unknow,please query in include/linux/in.h\n");
     70         }
     71     }
     72
     73     return 0;
     74 }
     75
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值