Virtual NIC Tun/tap under Linux

Source: Internet
Author: User

#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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.