1#include "faketcp.h" 2 3#include <stdio.h> 4#include <stdlib.h> 5#include <string.h> 6#include <unistd.h> 7#include <netinet/ip.h> 8#include <linux/if_ether.h> 9 10int main() 11{ 12 char ifname[IFNAMSIZ] = "tun%d"; 13 int fd = tun_alloc(ifname); 14 15 if (fd < 0) 16 { 17 fprintf(stderr, "tunnel interface allocation failed\n"); 18 exit(1); 19 } 20 21 printf("allocted tunnel interface %s\n", ifname); 22 sleep(1); 23 24 for (;;) 25 { 26 union 27 { 28 unsigned char buf[ETH_FRAME_LEN]; 29 struct iphdr iphdr; 30 }; 31 32 const int iphdr_size = sizeof iphdr; 33 34 int nread = read(fd, buf, sizeof(buf)); 35 if (nread < 0) 36 { 37 perror("read"); 38 close(fd); 39 exit(1); 40 } 41 printf("read %d bytes from tunnel interface %s.\n", nread, ifname); 42 43 const int iphdr_len = iphdr.ihl*4; 44 if (nread >= iphdr_size 45 && iphdr.version == 4 46 && iphdr_len >= iphdr_size 47 && iphdr_len <= nread 48 && iphdr.tot_len == htons(nread) 49 && in_checksum(buf, iphdr_len) == 0) 50 { 51 const void* payload = buf + iphdr_len; 52 if (iphdr.protocol == IPPROTO_ICMP) 53 { 54 icmp_input(fd, buf, payload, nread); 55 } 56 } 57 else 58 { 59 printf("bad packet\n"); 60 for (int i = 0; i < nread; ++i) 61 { 62 if (i % 4 == 0) printf("\n"); 63 printf("%02x ", buf[i]); 64 } 65 printf("\n"); 66 } 67 } 68 69 return 0; 70} 71