@@ -24,6 +24,8 @@ use std::net::{Ipv4Addr, Ipv6Addr};
2424 target_os = "watchos" ,
2525 target_os = "illumos" ,
2626 target_os = "solaris" ,
27+ target_os = "linux" ,
28+ target_os = "android" ,
2729 )
2830) ) ]
2931use std:: num:: NonZeroU32 ;
@@ -1847,6 +1849,29 @@ impl crate::Socket {
18471849 unsafe { setsockopt ( self . as_raw ( ) , IPPROTO_IP , libc:: IP_BOUND_IF , index) }
18481850 }
18491851
1852+ /// Sets the value for `SO_BINDTOIFINDEX` option on this socket.
1853+ ///
1854+ /// If a socket is bound to an interface, only packets received from that
1855+ /// particular interface are processed by the socket.
1856+ ///
1857+ /// If `interface` is `None`, the binding is removed. If the `interface`
1858+ /// index is not valid, an error is returned.
1859+ ///
1860+ /// One can use [`libc::if_nametoindex`] to convert an interface alias to an
1861+ /// index.
1862+ #[ cfg( all( feature = "all" , any( target_os = "linux" , target_os = "android" , ) ) ) ]
1863+ pub fn bind_device_by_index_v4 ( & self , interface : Option < NonZeroU32 > ) -> io:: Result < ( ) > {
1864+ let index = interface. map_or ( 0 , NonZeroU32 :: get) ;
1865+ unsafe {
1866+ setsockopt (
1867+ self . as_raw ( ) ,
1868+ libc:: SOL_SOCKET ,
1869+ libc:: SO_BINDTOIFINDEX ,
1870+ index,
1871+ )
1872+ }
1873+ }
1874+
18501875 /// Sets the value for `IPV6_BOUND_IF` option on this socket.
18511876 ///
18521877 /// If a socket is bound to an interface, only packets received from that
@@ -1874,6 +1899,21 @@ impl crate::Socket {
18741899 unsafe { setsockopt ( self . as_raw ( ) , IPPROTO_IPV6 , libc:: IPV6_BOUND_IF , index) }
18751900 }
18761901
1902+ /// Sets the value for `SO_BINDTOIFINDEX` option on this socket.
1903+ ///
1904+ /// If a socket is bound to an interface, only packets received from that
1905+ /// particular interface are processed by the socket.
1906+ ///
1907+ /// If `interface` is `None`, the binding is removed. If the `interface`
1908+ /// index is not valid, an error is returned.
1909+ ///
1910+ /// One can use [`libc::if_nametoindex`] to convert an interface alias to an
1911+ /// index.
1912+ #[ cfg( all( feature = "all" , any( target_os = "linux" , target_os = "android" , ) ) ) ]
1913+ pub fn bind_device_by_index_v6 ( & self , interface : Option < NonZeroU32 > ) -> io:: Result < ( ) > {
1914+ self . bind_device_by_index_v4 ( interface) // socket layer option, no IP version dependency
1915+ }
1916+
18771917 /// Gets the value for `IP_BOUND_IF` option on this socket, i.e. the index
18781918 /// for the interface to which the socket is bound.
18791919 ///
0 commit comments