@zwh8800
2017-08-23T10:02:40.000000Z
字数 1103
阅读 191296
blog
归档
网络编程
tun/tap
Linux
功能: 创建tun接口, 处理ping数据报
#include <linux/if_tun.h>
#include <net/if.h> /* for struct ifreq */
#include <sys/types.h> /* for open() */
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h> /* for bzero() */
#include <sys/ioctl.h>
#include <unistd.h>
#define BUF_SIZE 4096
#define SWAP(a, b, size) \
do { \
char t[size]; \
memcpy(t, &a, size); \
memcpy(&a, &b, size); \
memcpy(&b, t, size); \
}while (0)
int main()
{
struct ifreq ifr;
int fd, n;
char buf[BUF_SIZE];
if ((fd = open("/dev/net/tun", O_RDWR)) == -1)
{
perror("open");
exit(errno);
}
bzero(&ifr, sizeof(ifr));
ifr.ifr_flags = IFF_TUN | IFF_NO_PI;
strncpy(ifr.ifr_name, "", IFNAMSIZ);
if (ioctl(fd, TUNSETIFF, &ifr) == -1)
{
perror("ioctl");
exit(errno);
}
printf("ifname is %s\n", ifr.ifr_name);
while (1)
{
if ((n = read(fd, buf, BUF_SIZE)) == -1)
{
perror("read");
exit(errno);
}
else if (n == 0)
{
exit(0);
}
printf("%d bytes read\n", n);
SWAP(buf[12], buf[16], 4); /* swap ip */
buf[20] = 0;
(*((unsigned short*)&buf[22])) += 8;
if ((n = write(fd, buf, n)) <= 0)
{
perror("write");
exit(errno);
}
printf("%d bytes written\n", n);
}
return 0;
}
sudo ifconfig tun0 192.168.0.1/24 pointopoint 192.168.0.2 up
ping 192.168.0.2