Skip to content

Commit

Permalink
Add support to attach filter to a socket
Browse files Browse the repository at this point in the history
  • Loading branch information
hhyhhy authored Nov 9, 2021
1 parent 5c7b03f commit 6601ed1
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 1 deletion.
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ rustdoc-args = ["--cfg", "docsrs"]
features = ["all"]

[target."cfg(unix)".dependencies]
libc = "0.2.96"
libc = "0.2.107"

[target."cfg(windows)".dependencies]
winapi = { version = "0.3.9", features = ["handleapi", "ws2ipdef", "ws2tcpip"] }
Expand Down
31 changes: 31 additions & 0 deletions src/sys/unix.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1773,6 +1773,37 @@ impl crate::Socket {
})
}
}

/// Attach Berkeley Packet Filter(BPF) on this socket.
///
/// BPF allows a user-space program to attach a filter onto any socket
/// and allow or disallow certain types of data to come through the socket.
///
/// For more information about this option, see [filter](https://www.kernel.org/doc/html/v5.12/networking/filter.html)
#[cfg(all(feature = "all", any(target_os = "linux", target_os = "android")))]
pub fn attach_filter(&self, filters: &[libc::sock_filter]) -> io::Result<()> {
let prog = libc::sock_fprog {
len: filters.len() as u16,
filter: filters.as_ptr() as *mut _,
};

unsafe {
setsockopt(
self.as_raw(),
libc::SOL_SOCKET,
libc::SO_ATTACH_FILTER,
prog,
)
}
}

/// Detach Berkeley Packet Filter(BPF) from this socket.
///
/// For more information about this option, see [`attach_filter`]
#[cfg(all(feature = "all", any(target_os = "linux", target_os = "android")))]
pub fn detach_filter(&self) -> io::Result<()> {
unsafe { setsockopt(self.as_raw(), libc::SOL_SOCKET, libc::SO_DETACH_FILTER, 0) }
}
}

#[cfg_attr(docsrs, doc(cfg(unix)))]
Expand Down

0 comments on commit 6601ed1

Please sign in to comment.