gpt4 book ai didi

linux - 如何使用nix的ioctl?

转载 作者:IT王子 更新时间:2023-10-29 00:19:57 25 4
gpt4 key购买 nike

我想从 Rust 调用 ioctl。我知道我应该使用 the nix crate ,但究竟如何?从文档中看不清楚。

我有这个 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 crate 做同样的事情? nix crate 中没有 TUN* 常量,并且不清楚如何使用 ioctl 宏。

最佳答案

rust-spidev 中有一些示例用法.我会尝试将其应用到您的代码中。

TUNSETIFFdefined作为:

#define TUNSETIFF     _IOW('T', 202, int)

在 Rust 中使用 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);

上面的宏将定义函数,您可以这样调用它:

let err = unsafe { tun_set_iff(fd, ifr) }; // assuming ifr is an u32

关于linux - 如何使用nix的ioctl?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41478901/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com