[关闭]
@zwh8800 2017-08-23T02:02:40.000000Z 字数 1103 阅读 191166

linux tun/tap编程

blog 归档 网络编程 tun/tap Linux


功能: 创建tun接口, 处理ping数据报


  1. #include <linux/if_tun.h>
  2. #include <net/if.h> /* for struct ifreq */
  3. #include <sys/types.h> /* for open() */
  4. #include <sys/stat.h>
  5. #include <fcntl.h>
  6. #include <stdio.h>
  7. #include <stdlib.h>
  8. #include <errno.h>
  9. #include <string.h> /* for bzero() */
  10. #include <sys/ioctl.h>
  11. #include <unistd.h>
  12. #define BUF_SIZE 4096
  13. #define SWAP(a, b, size) \
  14. do { \
  15. char t[size]; \
  16. memcpy(t, &a, size); \
  17. memcpy(&a, &b, size); \
  18. memcpy(&b, t, size); \
  19. }while (0)
  20. int main()
  21. {
  22. struct ifreq ifr;
  23. int fd, n;
  24. char buf[BUF_SIZE];
  25. if ((fd = open("/dev/net/tun", O_RDWR)) == -1)
  26. {
  27. perror("open");
  28. exit(errno);
  29. }
  30. bzero(&ifr, sizeof(ifr));
  31. ifr.ifr_flags = IFF_TUN | IFF_NO_PI;
  32. strncpy(ifr.ifr_name, "", IFNAMSIZ);
  33. if (ioctl(fd, TUNSETIFF, &ifr) == -1)
  34. {
  35. perror("ioctl");
  36. exit(errno);
  37. }
  38. printf("ifname is %s\n", ifr.ifr_name);
  39. while (1)
  40. {
  41. if ((n = read(fd, buf, BUF_SIZE)) == -1)
  42. {
  43. perror("read");
  44. exit(errno);
  45. }
  46. else if (n == 0)
  47. {
  48. exit(0);
  49. }
  50. printf("%d bytes read\n", n);
  51. SWAP(buf[12], buf[16], 4); /* swap ip */
  52. buf[20] = 0;
  53. (*((unsigned short*)&buf[22])) += 8;
  54. if ((n = write(fd, buf, n)) <= 0)
  55. {
  56. perror("write");
  57. exit(errno);
  58. }
  59. printf("%d bytes written\n", n);
  60. }
  61. return 0;
  62. }
  1. sudo ifconfig tun0 192.168.0.1/24 pointopoint 192.168.0.2 up
  2. ping 192.168.0.2
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注