网络第三课(1)网络抓 包

来源:互联网 发布:知耻而后勇下一句 编辑:程序博客网 时间:2024/05/23 12:38

网络学习第三课:网络抓包文件。

通过网卡,我们来实现了抓 包。


#include <stdio.h>

#include <sys/socket.h>
#include <linux/if_ether.h>

int main()
{
    int fd = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL));//建立套接口。
    if(fd < 0){
        perror("socket");
        return 1;
    }
    
    unsigned char buff[1024] = {0};
    int ret = 0;
    struct sockaddr aa;
    int len = 0;
    while(1){
        memset(buff, 0, 1024);
        ret = read(fd, buff, 1024);//从套接口读取数据,到我们的buff中。
        if(ret < 0){
            perror("read");
            return 1;
        }
    
        int i = 0;

        if(ntohs(*(unsigned short *)(buff + 14 + 20 + 2)) != 53)//判断这udp协议上的,应用dns:dns对应用的端口号是53;http:80

//最后将这个端口号,转换为host主机字节序。

            continue;

        printf("\n\n");
        
        for(i=0; i<ret; i++)
        {
            printf("%0x\t", buff[i] & 0xff);    
            if(!((i + 1) % 8))
                printf("\n");
        }
        printf("\n\n");
    }
    
}