码迷,mamicode.com
首页 > 其他好文 > 详细

利用原始套接字实现一个简单的采集网络数据包

时间:2015-09-25 17:57:59      阅读:187      评论:0      收藏:0      [点我收藏+]

标签:

//利用原始套接字实现一个简单的采集网络数据包,并进行反向解析IP,MAC地址#include <stdio.h>
#include <sys/socket.h>
#include <unistd.h>
#include <sys/types.h>
#include <linux/if_ether.h>
#include <linux/in.h>

#define BUFFER_MAX 2048

int main(int argc, char **argv)
{
    int rawsock;
    char buffer[BUFFER_MAX];
    char *ethhead;
    char *iphead;
    char *phead;
   
    //创建原始套接字
    if((rawsock=socket(PF_PACKET,SOCK_RAW,htons(ETH_P_IP)))<0){
        printf("error:create raw socket!\n");
        exit(0);
    }
   
    long framecount =0;
   
    while(1){
        int readnum = recvfrom(rawsock,buffer,2048,0,NULL,NULL);
       
        if(readnum<42){
            printf("error:header is incomplete!\n");
            exit(0);
        }
       
        ethhead=(char*)buffer;
        phead=ethhead;
        int ethernetmask=0XFF;
        framecount++;
       
        printf("---------------AnalysisiPacket[%d]---------------\n",framecount);
        printf("MAC:");
        int i=6;
        for(;i<=11;i++)
            printf("%.2X:",phead[i]&ethernetmask);
        printf("------->");
        for(i=0;i<=5;i++)
            printf("%.2X:",phead[i]&ethernetmask);
        printf("\n");
       
        iphead=ethhead+14;
        phead=iphead+12;
       
        printf("IP:");
        for(i=0;i<=3;i++){
            printf("%d",phead[i]&ethernetmask);
            if(i!=3)
                printf(".");
        }
        printf("------->");
        for(i=4;i<=7;i++){
            printf("%d",phead[i]&ethernetmask);
            if(i!=7)
                printf(".");
        }
        printf("\n");
       
        int prototype=(iphead+9)[0];
        phead=iphead+20;
       
        printf("Protocol:");
        switch(prototype){
        case IPPROTO_ICMP:
            printf("ICMP\n");
            break;
        case IPPROTO_IGMP:
            printf("IGMP\n");
            break;
        case IPPROTO_IPIP:
            printf("IP");
            break;
        case IPPROTO_TCP:
            printf("TCP|source port: %u |",(phead[0]<<8)&0XFF00|phead[1]&0XFF);
            printf("destport: %u\n",(phead[2]<<8)&0XFF00|phead[3]&0XFF);
            break;
        case IPPROTO_UDP:
            printf("UDP|source port: %u |",(phead[0]<<8)&0XFF00|phead[1]&0XFF);
            printf("destport: %u\n",(phead[2]<<8)&0XFF00|phead[3]&0XFF);
            break;
        case IPPROTO_RAW:
            printf("RAW\n");
            break;
        default:
            printf("Unkown\n");   
        }
        printf("-----------------end--------------------");
    }
   
    return 0;
}

利用原始套接字实现一个简单的采集网络数据包

标签:

原文地址:http://www.cnblogs.com/ehui/p/4838730.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!