Description
TUN/TAP provides packet reception and transmission for user space programs.
It can be seen as a simple Point-to-Point or Ethernet device, which,
instead of receiving packets from physical media, receives them from
user space program and instead of sending packets via physical media
writes them to the user space program.
/* demo.c */ #include <fcntl.h> #include <string.h> #include <stdio.h> #include <stdlib.h> #include <sys/ioctl.h> #include <sys/types.h> #include <sys/socket.h> #include <linux/if.h> #include <linux/if_tun.h> int tun_open(char *devname) { struct ifreq ifr; int fd, err; if ( (fd = open("/dev/net/tun", O_RDWR)) == -1 ) { perror("open /dev/net/tun"); return -1; } memset(&ifr, 0, sizeof(ifr)); ifr.ifr_flags = IFF_TUN; strncpy(ifr.ifr_name, devname, IFNAMSIZ); if ( (err = ioctl(fd, TUNSETIFF, (void *) &ifr)) == -1 ) { perror("ioctl TUNSETIFF"); close(fd); return -1; } return fd; } int main(int argc, char **argv) { int i, fd, nbytes; char buf[2048]; fd = tun_open("tun0") ; printf("Device tun0 opened\n"); while(1) { nbytes = read(fd, buf, sizeof(buf)); printf("Read %d bytes from tun0\n", nbytes); for( i = 0; i < nbytes; i++) printf("%02x ", buf[i]); printf("\n"); } return 0; }
Terminal1:
[[email protected] sf_share]$ make demo
cc demo.c -o demo
[[email protected] sf_share]$ ./demo
Device tun0 opened
Terminal2:
[[email protected] sf_share]$ ifconfig tun0 172.16.0.0/16 up
[[email protected] sf_share]$ ping 172.16.66.88
Termina 1 OutPut:
Read 88 bytes from tun0
00 00 08 00 45 00 00 54 00 00 40 00 40 01 7e ffffff87 ffffffac 10 00 00 ffffffac 10 64 01 08 00 05 ffffffdc 73 0c 00 01 ffffffb2 38 24 58 00 00 00 00 ffffffe2 ffffffb2 07 00 00 00 00 00 10 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f 20 21 22 23 24 25 26 27 28 29 2a 2b 2c 2d 2e 2f 30 31 32 33 34 35 36 37
Read 88 bytes from tun0
00 00 08 00 45 00 00 54 00 00 40 00 40 01 7e ffffff87 ffffffac 10 00 00 ffffffac 10 64 01 08 00 2b ffffffdc 73 0c 00 02 ffffffb3 38 24 58 00 00 00 00 ffffffbb ffffffb1 07 00 00 00 00 00 10 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f 20 21 22 23 24 25 26 27 28 29 2a 2b 2c 2d 2e 2f 30 31 32 33 34 35 36 37
Read 88 bytes from tun0
00 00 08 00 45 00 00 54 00 00 40 00 40 01 7e ffffff87 ffffffac 10 00 00 ffffffac 10 64 01 08 00 5f ffffffdb 73 0c 00 03 ffffffb4 38 24 58 00 00 00 00 ffffff86 ffffffb1 07 00 00 00 00 00 10 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f 20 21 22 23 24 25 26 27 28 29 2a 2b 2c 2d 2e 2f 30 31 32 33 34 35 36 37