Raw Socket(原始套接字)实现Sniffer(嗅探)

参考资料:

  https://www.xuebuyuan.com/3190946.html

  https://blog.csdn.net/zxygww/article/details/52093308

 

    int socketfd = socket(AF_INET,SOCK_RAW,IPPROTO_ICMP);/*在网络层使用的原始套接字*/

    int socketfd = socket(PF_PACKET,SOCK_RAW,htons(ETH_P_IP));/*在链路层使用*/

 

  实验下图所示程序能够抓到packet。

#include <stdio.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <linux/if_ether.h>
#include <linux/in.h>

#define BUFFER_MAX 2048

int main()
{
    int sockfd, n_read, proto;
    char buff[BUFFER_MAX] = {0};


    //创建socket
    sockfd = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_IP));
    if (sockfd < 0) {
        perror("sock ");
        return -1;
    }

    while (1) {
        n_read = recvfrom(sockfd, buff, sizeof(buff), 0, NULL, NULL);

        if (n_read < 42) {
            fprintf(stderr, "packet corrupt\n");
            continue;
        }

        //报文解析
        {
            char *p = buff;

            printf("mac: %02x%02x%02x%02x%02x%02x===>%02x%02x%02x%02x%02x%02x\n",
                    p[6]&0xff, p[7]&0xff, p[8]&0xff, p[9]&0xff, p[10]&0xff, p[11]&0xff,
                    p[0]&0xff, p[1]&0xff, p[2]&0xff, p[3]&0xff, p[4]&0xff, p[5]&0xff);
        }
    }

    return 0;
}

 

posted on 2019-03-19 21:04  rivsidn  阅读(476)  评论(0编辑  收藏  举报

导航