我的代码
https://github.com/liuqun/demo-linux-tun-virtual-netcard/blob/master/demo-1-ioctl/src/main.c
代码片段1
以下代码节选自"openV屁N"的源码tun.c文件:
openV屁N封装了一组读写函数如下:
open_tun(dev_name, dev_type, dev_node, tuntap上下文)打开Tun虚拟网卡
close_tun(tuntap上下文)
n_bytes = write_tun(tuntap上下文, buf, len)
n_bytes = read_tun(tuntap上下文, buf, len)
int write_tun(struct tuntap *tt, uint8_t *buf, int len)
{
return write(tt->fd, buf, len);
}
int read_tun(struct tuntap *tt, uint8_t *buf, int len)
{
return read(tt->fd, buf, len);
}
void open_tun(const char *dev, const char *dev_type, const char *dev_node, struct tuntap *tt)
{
struct ifreq ifr;
/*
* We handle --dev null specially, we do not open /dev/null for this.
*/
if (tt->type == DEV_TYPE_NULL)
{
open_null(tt);
}
else
{
/*
* Process --dev-node
*/
const char *node = dev_node;
if (!node)
{
node = "/dev/net/tun";
}
/*
* Open the interface
*/
if ((tt->fd = open(node, O_RDWR)) < 0)
{
msg(M_ERR, "ERROR: Cannot open TUN/TAP dev %s", node);
}
/*
* Process --tun-ipv6
*/
CLEAR(ifr);
ifr.ifr_flags = IFF_NO_PI;
#if defined(IFF_ONE_QUEUE) && defined(SIOCSIFTXQLEN)
ifr.ifr_flags |= IFF_ONE_QUEUE;
#endif
/*
* Figure out if tun or tap device
*/
if (tt->type == DEV_TYPE_TUN)
{
ifr.ifr_flags |= IFF_TUN;
}
else if (tt->type == DEV_TYPE_TAP)
{
ifr.ifr_flags |= IFF_TAP;
}
else
{
msg(M_FATAL, "I don't reco