qfedu-network-advanced-level/day6/n2.c

67 lines
1.9 KiB
C
Raw Permalink Normal View History

2023-09-11 20:58:01 +08:00
/*拆解到IP报文*/
#include <netinet/ether.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
int main(int argc, char const *argv[])
{
// 创建原始套接字
int sock_fd = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL));
if (sock_fd < 0)
{
perror("raw socket");
return -1;
}
printf("原始套接字创建成功\n");
// 多次接收数据
while (1)
{
// 接链路层的数据报文(MAC报文)
unsigned char buf[1518] = ""; // 记得使用无符号类型
int len = recvfrom(sock_fd, buf, sizeof(buf), 0, NULL, NULL);
if (len < 18)
{
perror("recvfrom");
continue;
}
// 拆解 MAC 数据报文
unsigned char dst_mac[18] = ""; // 目的MAC地址
unsigned char src_mac[18] = ""; // 源MAC地址
unsigned short mac_type = ntohs(*((unsigned short *)(buf + 12)));
// sprintf(src_mac, "%02x:%02x:%02x:%02x:%02x:%02x", buf[6], buf[7], buf[8], buf[9], buf[10], buf[11]);
// sprintf(dst_mac, "%02x:%02x:%02x:%02x:%02x:%02x", buf[0], buf[1], buf[2], buf[3], buf[4], buf[5]);
sprintf(src_mac, "%02x:%02x:%02x:%02x:%02x:%02x", buf[6], buf[7], buf[8], buf[9], buf[10], buf[11]);
sprintf(dst_mac, "%02x:%02x:%02x:%02x:%02x:%02x", buf[0], buf[1], buf[2], buf[3], buf[4], buf[5]);
// if (strncmp(src_mac, "00:00:00", 8) != 0)
printf("dst_mac %s -> src_mac %s type(%#x)\n", dst_mac, src_mac, mac_type);
sleep(1);
switch (mac_type)
{
case 0x0800:
printf("-----ip 数据包-----\n");
break;
case 0x0806:
printf("-----ARP 数据包-----\n");
break;
case 0x8035:
printf("-----RARP 数据包-----\n");
break;
}
}
close(sock_fd);
return 0;
}