如何使用nix的ioctl? [英] How to use nix's ioctl?
本文介绍了如何使用nix的ioctl?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想从Rust调用 ioctl
.我知道我应该使用 nix板条箱,但是究竟是什么?从文档中尚不清楚.
I want to call ioctl
from Rust. I know that I should use the nix crate, but how exactly? From the documentation it's not clear.
我有这个C:
int tun_open(char *devname)
{
struct ifreq ifr;
int fd, err;
if ( (fd = open("/dev/net/tun", O_RDWR)) == -1 ) {
perror("open /dev/net/tun");exit(1);
}
memset(&ifr, 0, sizeof(ifr));
ifr.ifr_flags = IFF_TUN;
strncpy(ifr.ifr_name, devname, IFNAMSIZ);
/* ioctl will use if_name as the name of TUN
* interface to open: "tun0", etc. */
if ( (err = ioctl(fd, TUNSETIFF, (void *) &ifr)) == -1 ) {
perror("ioctl TUNSETIFF");close(fd);exit(1);
}
//..........
我如何使用nix板条箱做同样的事情?nix板条箱中没有 TUN *
常量,目前尚不清楚如何使用 ioctl
宏.
How would I do that same thing using the nix crate? There are no TUN*
constants in the nix crate and it isn't clear how to use the ioctl
macro.
推荐答案
There is some example usage in rust-spidev. I will try to apply that to your code.
TUNSETIFF
是定义的为:
#define TUNSETIFF _IOW('T', 202, int)
使用nix在Rust中就是这样:
That would be this in Rust using nix:
const TUN_IOC_MAGIC: u8 = 'T' as u8;
const TUN_IOC_SET_IFF: u8 = 202;
ioctl!(write tun_set_iff with TUN_IOC_MAGIC, TUN_IOC_SET_IFF; u32);
上面的宏将定义函数,您可以像这样调用该函数:
The above macro will define the function, which you can call like this:
let err = unsafe { tun_set_iff(fd, ifr) }; // assuming ifr is an u32
这篇关于如何使用nix的ioctl?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文