关闭

Linux网络编程—原始套接字实例:MAC 头部报文分析

发表于:2015-4-02 09:58

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:Mike__Jiang    来源:51Testing软件测试网采编

  记得以管理者权限运行程序:
  每个报文头部都有一个相应的结构体,通过这些结构体对报文进行相应的组包或拆包会方便很多。
  ubuntu 12.04 中描述网络协议结构的文件如下:
  以太网头部(所需要头文件:#include <net/ethernet.h>):
  上面的例子,改为用结构体实现,如下:
[objc] view plaincopy在CODE上查看代码片派生到我的代码片
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netinet/ether.h>
#include <net/ethernet.h>         // 以太网头部 头文件
#include <netinet/ip.h>           // ip头部 头文件
// #include <net/if_arp.h>            // arp头部 头文件
int main(int argc,charchar *argv[])
{
int i = 0;
unsigned char buf[1024] = "";
int sock_raw_fd = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL));
while(1)
{
unsigned char src_mac[18] = "";
unsigned char dst_mac[18] = "";
//获取链路层的数据帧
recvfrom(sock_raw_fd, buf, sizeof(buf),0,NULL,NULL);
//从数据中提取mac首部信息(14个字节)
struct ether_header *ethdr = NULL;
ethdr = (struct ether_header *)buf;
//从buf里提取目的mac、源mac
sprintf(dst_mac,"%02x:%02x:%02x:%02x:%02x:%02x", ethdr->ether_dhost[0], ethdr->ether_dhost[1],ethdr->ether_dhost[2],ethdr->ether_dhost[3],ethdr->ether_dhost[4],ethdr->ether_dhost[5]);
sprintf(src_mac,"%02x:%02x:%02x:%02x:%02x:%02x", ethdr->ether_shost[0], ethdr->ether_shost[1],ethdr->ether_shost[2],ethdr->ether_shost[3],ethdr->ether_shost[4],ethdr->ether_shost[5]);
//判断是否为IP数据包
if( 0x0800 == ntohs(ethdr->ether_type) )
{
printf("______________IP数据报_______________\n");
printf("MAC:%s >> %s\n",src_mac,dst_mac);
}//0x0806为ARP数据包, 0x8035为RARP数据包
else if( 0x0806 == ntohs(ethdr->ether_type) || 0x8035 == ntohs(ethdr->ether_type) )
{
printf("______________ARP数据报_______________\n");
printf("MAC:%s >> %s\n",src_mac,dst_mac);
}
}
return 0;
}

22/2<12
《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号