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;
}

 

转载于:https://www.cnblogs.com/rivsidn/p/10561342.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值