模拟抓包,并且解析报文。
这边先贴上代码和部分资料。详细解释以后再写:
1.以太网帧
2.IP报文
3.TCP报文
4.UDP报文
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <net/ethernet.h>
#include <netinet/in.h>
#include <linux/if_ether.h>
#include <linux/if_packet.h>
#include <linux/if_arp.h>
#include <stdio.h>
//解析出mac地址
void dump_mac(const char* header, char* buf, int start)
{
printf("%s", header);
int i;
for(i=start; i<6+start; ++i)
{
printf("%02x:", (int)(unsigned char)buf[i]);
}
printf("\n");
}
//解析出以太网帧类型
unsigned short get_type(char* buf)
{
unsigned short type = *(unsigned short*)(buf+12);
return ntohs(type);
}
//解析出IP报文的8位协议类型 TCP:6/UDP:17
unsigned char get_ptype(unsigned char* ip)
{
return ip[9];
}
//ip报文开始的位置
unsigned char* get_ip_start(char* buf)
{
return buf + 14;
}
//TCP报文开始的位置
unsigned char* get_tcp_start(unsigned char* ip)
{
// 先得到首部长度
int hlen = (ip[0] & 0xf) * 4;
printf("hlen = %d\n", hlen); // 20
return ip + hlen;
}
//TCP报文数据
unsigned char* get_tcp_data(unsigned char* tcp)
{
int hlen = ((tcp[12] & 0xf0) >> 4) * 4;
return tcp + hlen;
}
void handle(char* buf, int length)
{
unsigned short type = get_type(buf);
if(type != 0x0800)
return;
// 只对IP报文进行分析
unsigned char* ip = get_ip_start(buf);
// 协议类型
unsigned char ptype = get_ptype(ip);
if(ptype != 6)
{
return; // 只对TCP进行分析
}
unsigned char* tcp = get_tcp_start(ip);
unsigned char* tcp_data = get_tcp_data(tcp);
printf("%s\n\n\n", tcp_data);
}
int main()
{
// 创建了一个原始套接字
// int sock = socket(AF_PACKET, SOCK_RAW, htons(IPPROTO_RAW));
int sock = socket(AF_PACKET, SOCK_RAW, htons(ETH_P_ALL));
if(sock < 0)
{
perror("socket");
return 0;
}
// 获得硬件信息,获取接口的下标
struct ifreq ifstruct;
strcpy(ifstruct.ifr_name, "eth0");
// 获取接口index
ioctl(sock, SIOCGIFINDEX, &ifstruct);
// 获取本地MAC地址
ioctl(sock, SIOCGIFHWADDR, &ifstruct);
// 获取网卡设置
ioctl(sock, SIOCGIFFLAGS, &ifstruct);
// 设置混杂模式
ifstruct.ifr_flags |= IFF_PROMISC;
// 绑定网口
struct sockaddr_ll sll;
sll.sll_family = AF_PACKET;
sll.sll_ifindex = ifstruct.ifr_ifindex;
sll.sll_protocol = htons(ETH_P_ALL);
sll.sll_hatype = ARPHRD_ETHER;
sll.sll_pkttype = PACKET_OTHERHOST;
sll.sll_halen = ETH_ALEN; //MAC地址的长度
sll.sll_addr[6] = 0;
sll.sll_addr[7] = 0;
bind(sock, (struct sockaddr *)&sll, sizeof(struct sockaddr_ll));
// --------------------原始套接字创建完成--------------------------------
char buf[1514];
while(1)
{
int ret = read(sock, buf, sizeof(buf));
if(ret <= 0)
{
perror("read");
return 0;
}
handle(buf, ret);
}
}