Skip to content

Added Socket::set_multicast_if_v4_n to set interface by index (#458) #582

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -189,7 +189,6 @@ pub use sockaddr::{sa_family_t, socklen_t, SockAddr, SockAddrStorage};
#[cfg(not(any(
target_os = "haiku",
target_os = "illumos",
target_os = "netbsd",
target_os = "redox",
target_os = "solaris",
)))]
Expand Down
49 changes: 48 additions & 1 deletion src/socket.rs
Original file line number Diff line number Diff line change
Expand Up @@ -821,7 +821,6 @@ fn set_common_flags(socket: Socket) -> io::Result<Socket> {
#[cfg(not(any(
target_os = "haiku",
target_os = "illumos",
target_os = "netbsd",
target_os = "redox",
target_os = "solaris",
)))]
Expand Down Expand Up @@ -1496,6 +1495,54 @@ impl Socket {
}
}

/// Set the value of the `IP_MULTICAST_IF` option for this socket.
///
/// Specifies the interface to use for routing multicast packets.
/// See [`InterfaceIndexOrAddress`].
#[cfg(all(
feature = "all",
any(
target_os = "freebsd",
target_os = "netbsd",
target_os = "linux",
target_os = "android",
target_os = "fuchsia",
)
))]
pub fn set_multicast_if_v4_n(&self, interface: &InterfaceIndexOrAddress) -> io::Result<()> {
#[cfg(any(
target_os = "freebsd",
target_os = "linux",
target_os = "android",
target_os = "fuchsia"
))]
{
// IP_MULTICAST_IF supports struct mreqn to set the interface
let mreqn = sys::to_mreqn(&Ipv4Addr::UNSPECIFIED, interface);
unsafe { setsockopt(self.as_raw(), sys::IPPROTO_IP, sys::IP_MULTICAST_IF, mreqn) }
}

#[cfg(target_os = "netbsd")]
{
// IP_MULTICAST_IF only supports struct in_addr to set the interface, but passing an
// address in the 0.0.0.0/8 range is interpreted as an interface index (in network
// byte order)
let addr = match interface {
InterfaceIndexOrAddress::Index(index) => {
if *index >= 0x0100_0000 {
return Err(io::Error::new(
io::ErrorKind::AddrNotAvailable,
"Interface index out of bounds",
));
}
Ipv4Addr::from_bits(*index)
}
InterfaceIndexOrAddress::Address(a) => *a,
};
unsafe { setsockopt(self.as_raw(), sys::IPPROTO_IP, sys::IP_MULTICAST_IF, addr) }
}
}

/// Get the value of the `IP_MULTICAST_LOOP` option for this socket.
///
/// For more information about this option, see [`set_multicast_loop_v4`].
Expand Down