ping/
fuchsia.rs

1// Copyright 2021 The Fuchsia Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#![deny(missing_docs)]
6
7use crate::{IcmpSocket, Ipv4, Ipv6};
8use core::task::{Context, Poll};
9use fuchsia_async as fasync;
10use futures::ready;
11
12impl<I> IcmpSocket<I> for fasync::net::DatagramSocket
13where
14    I: crate::IpExt,
15{
16    /// Async method for receiving an ICMP packet.
17    ///
18    /// See [`fuchsia_async::net::DatagramSocket::recv_from()`].
19    fn async_recv_from(
20        &self,
21        buf: &mut [u8],
22        cx: &mut Context<'_>,
23    ) -> Poll<std::io::Result<(usize, I::SockAddr)>> {
24        Poll::Ready(ready!(self.async_recv_from(buf, cx)).and_then(|(len, addr)| {
25            <I::SockAddr as crate::TryFromSockAddr>::try_from(addr).map(|addr| (len, addr))
26        }))
27    }
28
29    /// Async method for sending an ICMP packet.
30    ///
31    /// See [`fuchsia_async::net::DatagramSocket::send_to_vectored()`].
32    fn async_send_to_vectored(
33        &self,
34        bufs: &[std::io::IoSlice<'_>],
35        addr: &I::SockAddr,
36        cx: &mut Context<'_>,
37    ) -> Poll<std::io::Result<usize>> {
38        self.async_send_to_vectored(bufs, &(*addr).clone().into(), cx)
39    }
40
41    /// Binds this to an interface so that packets can only flow in/out via the specified
42    /// interface.
43    ///
44    /// Implemented by setting the `SO_BINDTODEVICE` socket option.
45    ///
46    /// See [`fuchsia_async::net::DatagramSocket::bind_device()`].
47    fn bind_device(&self, interface: Option<&[u8]>) -> std::io::Result<()> {
48        self.bind_device(interface)
49    }
50}
51
52/// Create a new ICMP socket.
53pub fn new_icmp_socket<I: IpExt>() -> std::io::Result<fasync::net::DatagramSocket> {
54    fasync::net::DatagramSocket::new(I::DOMAIN, Some(I::PROTOCOL))
55}
56
57/// Extension trait on [`crate::IpExt`] for Fuchsia-specific functionality.
58pub trait IpExt: crate::IpExt {
59    /// Socket domain.
60    const DOMAIN_FIDL: fidl_fuchsia_posix_socket::Domain;
61}
62
63impl IpExt for Ipv4 {
64    const DOMAIN_FIDL: fidl_fuchsia_posix_socket::Domain = fidl_fuchsia_posix_socket::Domain::Ipv4;
65}
66
67impl IpExt for Ipv6 {
68    const DOMAIN_FIDL: fidl_fuchsia_posix_socket::Domain = fidl_fuchsia_posix_socket::Domain::Ipv6;
69}