@@ -24,6 +24,8 @@ use std::net::{Ipv4Addr, Ipv6Addr};
24
24
target_os = "watchos" ,
25
25
target_os = "illumos" ,
26
26
target_os = "solaris" ,
27
+ target_os = "linux" ,
28
+ target_os = "android" ,
27
29
)
28
30
) ) ]
29
31
use std:: num:: NonZeroU32 ;
@@ -1847,6 +1849,28 @@ impl crate::Socket {
1847
1849
unsafe { setsockopt ( self . as_raw ( ) , IPPROTO_IP , libc:: IP_BOUND_IF , index) }
1848
1850
}
1849
1851
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(
1863
+ feature = "all" ,
1864
+ any(
1865
+ target_os = "linux" ,
1866
+ target_os = "android" ,
1867
+ )
1868
+ ) ) ]
1869
+ pub fn bind_device_by_index_v4 ( & self , interface : Option < NonZeroU32 > ) -> io:: Result < ( ) > {
1870
+ let index = interface. map_or ( 0 , NonZeroU32 :: get) ;
1871
+ unsafe { setsockopt ( self . as_raw ( ) , libc:: SOL_SOCKET , libc:: SO_BINDTOIFINDEX , index) }
1872
+ }
1873
+
1850
1874
/// Sets the value for `IPV6_BOUND_IF` option on this socket.
1851
1875
///
1852
1876
/// If a socket is bound to an interface, only packets received from that
@@ -1874,6 +1898,27 @@ impl crate::Socket {
1874
1898
unsafe { setsockopt ( self . as_raw ( ) , IPPROTO_IPV6 , libc:: IPV6_BOUND_IF , index) }
1875
1899
}
1876
1900
1901
+ /// Sets the value for `SO_BINDTOIFINDEX` option on this socket.
1902
+ ///
1903
+ /// If a socket is bound to an interface, only packets received from that
1904
+ /// particular interface are processed by the socket.
1905
+ ///
1906
+ /// If `interface` is `None`, the binding is removed. If the `interface`
1907
+ /// index is not valid, an error is returned.
1908
+ ///
1909
+ /// One can use [`libc::if_nametoindex`] to convert an interface alias to an
1910
+ /// index.
1911
+ #[ cfg( all(
1912
+ feature = "all" ,
1913
+ any(
1914
+ target_os = "linux" ,
1915
+ target_os = "android" ,
1916
+ )
1917
+ ) ) ]
1918
+ pub fn bind_device_by_index_v6 ( & self , interface : Option < NonZeroU32 > ) -> io:: Result < ( ) > {
1919
+ self . bind_device_by_index_v4 ( interface) // socket layer option, no IP version dependency
1920
+ }
1921
+
1877
1922
/// Gets the value for `IP_BOUND_IF` option on this socket, i.e. the index
1878
1923
/// for the interface to which the socket is bound.
1879
1924
///
0 commit comments