#include <stdio.h>
#include <string.h>
#include <linux/if_tun.h>
#include <sys/types.h>
#include <net/if.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/ioctl.h>
int Tun_create (char *dev, int flags)
{
struct Ifreq IFR;
int FD;
int cmd;
if (FD = open ("/dev/net/tun", O_RDWR)) < 0)
{
return FD;
}
memset (&IFR, 0, sizeof (IFR));
strcpy (Ifr.ifr_name, Dev);
Ifr.ifr_flags |= flags;
IOCTL (FD, Tunsetiff, (void *) &IFR);
return (FD);
}
int main (int argc, char *argv[])
{
Int Tun, ret;
unsigned char buf[4096];
unsigned char ip[4];
unsigned char IHL;
Tun = tun_create ("Tun0", Iff_tun | IFF_NO_PI);
if (Tun < 0)
{
Perror ("Tun_create");
return 1;
}
printf ("TUN name is%s\n", "tun0");
while (1)
{
ret = Read (tun, buf, sizeof (BUF));
if (Ret < 0)
{
Break
}
IHL = buf[0] & 0xf;
printf ("The length of the IP header is%d\n", IHL);
memcpy (IP, &buf[12], 4);
memcpy (&buf[12], &buf[16], 4);
memcpy (&buf[16], IP, 4);
buf[20] = 0;
* ((unsigned short*) &buf[22]) + = 8;
printf ("Read%d bytes\n", ret);
ret = Write (tun, buf, ret);
printf ("Write%d bytes\n", ret);
}
return 0;
}
This code is basically replicated on the network. However, the code on the network does not have the head file full, the harm I toss. There is nothing special to say, but one thing that is not clear is that see the red part. The IP header size is exactly 20 bytes, and the code actually operates in 21 and 23 bytes, which in principle is the option field. After the red code is commented out, the program can run normally, but the delay is increased by about 0.3ms. I don't understand!
Virtual NIC Tun/tap under Linux