@@ -17,8 +17,11 @@ use std::net::{Ipv4Addr, Ipv6Addr};
17
17
#[ cfg( all(
18
18
feature = "all" ,
19
19
any(
20
+ target_os = "android" ,
21
+ target_os = "fuchsia" ,
20
22
target_os = "ios" ,
21
23
target_os = "visionos" ,
24
+ target_os = "linux" ,
22
25
target_os = "macos" ,
23
26
target_os = "tvos" ,
24
27
target_os = "watchos" ,
@@ -1805,6 +1808,44 @@ impl crate::Socket {
1805
1808
. map ( |_| ( ) )
1806
1809
}
1807
1810
1811
+ /// Gets the value for the `SO_BINDTOIFINDEX` option on this socket.
1812
+ ///
1813
+ /// This value gets the socket binded device's interface index.
1814
+ #[ cfg( all(
1815
+ feature = "all" ,
1816
+ any( target_os = "android" , target_os = "fuchsia" , target_os = "linux" )
1817
+ ) ) ]
1818
+ pub fn device_index ( & self ) -> io:: Result < Option < NonZeroU32 > > {
1819
+ let index_raw = unsafe {
1820
+ getsockopt :: < libc:: c_uint > ( self . as_raw ( ) , libc:: SOL_SOCKET , libc:: SO_BINDTOIFINDEX ) ?
1821
+ } ;
1822
+ Ok ( NonZeroU32 :: new ( index_raw) )
1823
+ }
1824
+
1825
+ /// Sets the value for `SO_BINDTOIFINDEX` option on this socket.
1826
+ ///
1827
+ /// If a socket is bound to an interface, only packets received from that
1828
+ /// particular interface are processed by the socket. Note that this only
1829
+ /// works for some socket types, particularly `AF_INET` sockets.
1830
+ ///
1831
+ /// If `interface` is `None`, the binding is removed. If the `interface`
1832
+ /// index is not valid, an error is returned.
1833
+ #[ cfg( all(
1834
+ feature = "all" ,
1835
+ any( target_os = "android" , target_os = "fuchsia" , target_os = "linux" )
1836
+ ) ) ]
1837
+ pub fn bind_device_by_index ( & self , interface : Option < NonZeroU32 > ) -> io:: Result < ( ) > {
1838
+ let index = interface. map_or ( 0 , NonZeroU32 :: get) ;
1839
+ unsafe {
1840
+ setsockopt (
1841
+ self . as_raw ( ) ,
1842
+ libc:: SOL_SOCKET ,
1843
+ libc:: SO_BINDTOIFINDEX ,
1844
+ index as c_int ,
1845
+ )
1846
+ }
1847
+ }
1848
+
1808
1849
/// Sets the value for the `SO_SETFIB` option on this socket.
1809
1850
///
1810
1851
/// Bind socket to the specified forwarding table (VRF) on a FreeBSD.
0 commit comments