1 #include <stdio.h> 2 #include <unistd.h> 3 #include <linux/if_ether.h> 4 #include <linux/ip.h> 5 #include <linux/udp.h> 6 #include <linux/types.h> 7 8 void show_mac(const unsigned char *data); 9 void show_ip(const unsigned char *data); 10 void show_arp(const unsigned char *data); 11 void show_udp(const unsigned char *data); 12 void show_tcp(const unsigned char *data); 13 void show_app(const unsigned char *data); 14 15 int main() 16 { 17 unsigned char data[1024] = { 18 0x00, 0x26, 0xc6, 0x41, 0x06, 0xb2, 0x00, 0x26, 19 0xc6, 0x39, 0x8c, 0x36, 0x08, 0x00, 0x45, 0x00, 20 0x00, 0x20, 0x00, 0x00, 0x40, 0x00, 0x40, 0x11, 21 0x7a, 0x90, 0xc0, 0xa8, 0x1f, 0x72, 0xc0, 0xa8, 22 0x1f, 0x7a, 0x94, 0x2b, 0x25, 0x37, 0x00, 0x0c, 23 0xa0, 0x6d, 0x77, 0x61, 0x6e, 0x67 24 }; 25 26 show_mac(data); 27 28 } 29 30 void show_mac(const unsigned char *data) 31 { 32 struct ethhdr *eth = (struct ethhdr *)data; 33 printf("-------------物理层-------------\n"); 34 printf("目的MAC地址: %02x:%02x:%02x:%02x:%02x:%02x\n", 35 eth->h_dest[0], eth->h_dest[1], 36 eth->h_dest[2], eth->h_dest[3], 37 eth->h_dest[4], eth->h_dest[5] 38 ); 39 printf("源端MAC地址: %02x:%02x:%02x:%02x:%02x:%02x\n", 40 eth->h_source[0], eth->h_source[1], 41 eth->h_source[2], eth->h_source[3], 42 eth->h_source[4], eth->h_source[5] 43 ); 44 printf("使用的协议: %04x\n\n", ntohs(eth->h_proto)); 45 if(ntohs(eth->h_proto) == 0x0800) 46 show_ip(data); 47 if(ntohs(eth->h_proto) == 0x0806) 48 show_arp(data); 49 } 50 void show_ip(const unsigned char *data) 51 { 52 printf("-------------网络层-------------\n"); 53 54 struct iphdr *ip = (struct iphdr *)(data + sizeof(struct ethhdr)); 55 printf("版本号: %d\n", ip->version); 56 printf("IP首部长度: %d\n", (ip->ihl)*4); 57 printf("服务类型: %d\n", ip->tos); 58 printf("总长度: %d\n", ntohs(ip->tot_len)); 59 printf("标识: %d\n", ip->id); 60 printf("片偏移: %d\n", ip->frag_off); 61 printf("生存时间: %d\n", ip->ttl); 62 printf("上层使用协议: %d\n", ip->protocol); 63 printf("首部检验和: %d\n", ip->check); 64 printf("源IP地址: %s\n", inet_ntoa(ip->saddr)); 65 printf("目的IP地址: %s\n\n", inet_ntoa(ip->daddr)); 66 if(ip->protocol == 6) 67 show_tcp(data); 68 if(ip->protocol == 17) 69 show_udp(data); 70 } 71 void show_arp(const unsigned char *data) 72 { 73 74 } 75 void show_udp(const unsigned char *data) 76 { 77 printf("-------------传输层-------------\n"); 78 struct udphdr *udp = (struct udphdr *)(data + sizeof(struct ethhdr)+ sizeof(struct iphdr)); 79 printf("源端口号: %d\n", htons(udp->source)); 80 printf("目的端口号: %d\n", htons(udp->dest)); 81 printf("UDP长度: %d\n", htons(udp->len)); 82 printf("UDP检验和: %x\n\n", htons(udp->check)); 83 show_app(data); 84 } 85 void show_tcp(const unsigned char *data) 86 { 87 88 } 89 void show_app(const unsigned char *data) 90 { 91 printf("-------------应用层-------------\n"); 92 char *p = (char *)(data + sizeof(struct ethhdr)+ sizeof(struct iphdr)+sizeof(struct udphdr)); 93 printf("数据:%s\n\n", p); 94 95 }
时间: 2024-11-03 22:07:38