使用PF_PACKET和 SOCK_RAW探测网络包

接着上两篇文章:使用dev_add_pack注册新的以太网类型

使用PF_PACKET和SOCK_RAW发送自定义type以太网数据包

我们这一篇使用PF_PACKET和 SOCK_RAW捕抓我们发送新协议数据包。

先上码:

#include <stdio.h>
#include <errno.h>  
#include <unistd.h>
#include <sys/socket.h>
#include <sys/types.h>  
#include <linux/in.h>
#include <linux/if_ether.h>
#include <stdlib.h>

int main(int argc, char **argv) {
    int sock, n;
    char buffer[2048];
    unsigned char *data, *ethhead;


    if ( (sock=socket(PF_PACKET, SOCK_RAW,
                    htons(0x8874)))<0) {//0x8874是我自定义的新类型
        perror("socket");
        exit(1);
    }
    while (1) {
        printf("----------\n");
        n = recvfrom(sock,buffer,2048,0,NULL,NULL);
        printf("%d bytes read\n",n);

        if (n<42) {
            perror("recvfrom():");
            printf("Incomplete packet (errno is %d)\n",
                    errno);
            close(sock);
            exit(0);
        }
        ethhead = buffer;
        printf("Source MAC address: "
                "%02x:%02x:%02x:%02x:%02x:%02x\n",
                ethhead[0],ethhead[1],ethhead[2],
                ethhead[3],ethhead[4],ethhead[5]);
        printf("Destination MAC address: "
                "%02x:%02x:%02x:%02x:%02x:%02x\n",
                ethhead[6],ethhead[7],ethhead[8],
                ethhead[9],ethhead[10],ethhead[11]);
        printf("%x%x\n", ethhead[12],ethhead[13]);
        data=buffer+14;
        printf("%s\n",data);
    }
}

运行得知:

/tmp # ./netcat3 
----------
60 bytes read
Source MAC address: 00:0b:82:27:fd:e4
Destination MAC address: 00:15:17:28:e4:06
8874
hello world!
----------
60 bytes read
Source MAC address: 00:0b:82:27:fd:e4
Destination MAC address: 00:15:17:28:e4:06
8874
hello world!
----------


正确的捕捉到我们的新协议!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值