Skip to content

Commit 45b3609

Browse files
committed
Added bind_device_by_index_{v4,v6} for linux and android (rust-lang#569)
1 parent 33291e2 commit 45b3609

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

src/sys/unix.rs

+45
Original file line numberDiff line numberDiff line change
@@ -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
))]
2931
use std::num::NonZeroU32;
@@ -1847,6 +1849,28 @@ 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(
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+
18501874
/// Sets the value for `IPV6_BOUND_IF` option on this socket.
18511875
///
18521876
/// If a socket is bound to an interface, only packets received from that
@@ -1874,6 +1898,27 @@ impl crate::Socket {
18741898
unsafe { setsockopt(self.as_raw(), IPPROTO_IPV6, libc::IPV6_BOUND_IF, index) }
18751899
}
18761900

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+
18771922
/// Gets the value for `IP_BOUND_IF` option on this socket, i.e. the index
18781923
/// for the interface to which the socket is bound.
18791924
///

0 commit comments

Comments
 (0)