接着上两篇文章:使用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!
----------
正确的捕捉到我们的新协议!