How to use nix ioctl?

I want to call ioctl from Rust. I know that I should use nix crate , but how exactly? This is not clear from the documentation.

I have a 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); } //.......... 

How can I do the same using the nix box? There are no TUN* constants in the nix box, and it is unclear how to use the ioctl macro.

+5
source share
1 answer

There is an example of using rust-spidev . I will try to apply this to your code.

TUNSETIFF defined as:

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

This would be 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 a function that you can call as follows:

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

Source: https://habr.com/ru/post/1262334/


All Articles