intmain() { int tun_fd, nread; char buffer[4096]; char tun_name[IFNAMSIZ];
tun_name[0] = '\0';
/* Flags: IFF_TUN - TUN device (no Ethernet headers) * IFF_TAP - TAP device * IFF_NO_PI - Do not provide packet information */ tun_fd = tun_alloc(tun_name, IFF_TUN | IFF_NO_PI);
if (tun_fd < 0) { perror("Allocating interface"); exit(1); }
printf("Open tun/tap device: %s for reading...\n", tun_name); while (1) { unsignedchar ip[4]; // 收包 nread = read(tun_fd, buffer, sizeof(buffer)); if (nread < 0) { perror("Reading from interface"); close(tun_fd); exit(1); } printf("Read %d bytes from tun/tap device\n", nread); // 简单对收到的包调换一下顺序 memcpy(ip, &buffer[12], 4); memcpy(&buffer[12], &buffer[16], 4); memcpy(&buffer[16], ip, 4);
[root@localhost ~]# ping -c 4 10.1.1.3 PING 10.1.1.3 (10.1.1.3) 56(84) bytes of data. 64 bytes from 10.1.1.3: icmp_seq=1 ttl=64 time=0.133 ms 64 bytes from 10.1.1.3: icmp_seq=2 ttl=64 time=0.188 ms 64 bytes from 10.1.1.3: icmp_seq=3 ttl=64 time=0.092 ms 64 bytes from 10.1.1.3: icmp_seq=4 ttl=64 time=0.110 ms
--- 10.1.1.3 ping statistics --- 4 packets transmitted, 4 received, 0% packet loss, time 3290ms rtt min/avg/max/mdev = 0.092/0.130/0.188/0.038 ms
intmain() { int tun_fd, nread; char buffer[4096]; char tun_name[IFNAMSIZ];
tun_name[0] = '\0';
/* Flags: IFF_TUN - TUN device (no Ethernet headers) * IFF_TAP - TAP device * IFF_NO_PI - Do not provide packet information */ tun_fd = tun_alloc(tun_name, IFF_TUN | IFF_NO_PI);
if (tun_fd < 0) { perror("Allocating interface"); exit(1); }
printf("Open tun/tap device: %s for reading...\n", tun_name); while (1) { unsignedchar ip[4]; // 收包 nread = read(tun_fd, buffer, sizeof(buffer)); if (nread < 0) { perror("Reading from interface"); close(tun_fd); exit(1); } printf("Read %d bytes from tun/tap device\n", nread); // 简单对收到的包调换一下顺序 memcpy(ip, &buffer[12], 4); memcpy(&buffer[12], &buffer[16], 4); memcpy(&buffer[16], ip, 4);