nex_socket/
lib.rs

1//! Convenience sockets built on top of `socket2` and `tokio`.
2//!
3//! This crate provides synchronous and asynchronous helpers for TCP, UDP and
4//! ICMP. The goal is to simplify lower level socket configuration across
5//! platforms while still allowing direct access when needed.
6
7pub mod icmp;
8pub mod tcp;
9pub mod udp;
10
11use std::net::{IpAddr, SocketAddr};
12
13/// Represents the socket address family (IPv4 or IPv6)
14#[derive(Debug, Clone, Copy, PartialEq, Eq)]
15pub enum SocketFamily {
16    IPV4,
17    IPV6,
18}
19
20impl SocketFamily {
21    /// Returns the socket family of the IP address.
22    pub fn from_ip(ip: &IpAddr) -> Self {
23        match ip {
24            IpAddr::V4(_) => SocketFamily::IPV4,
25            IpAddr::V6(_) => SocketFamily::IPV6,
26        }
27    }
28
29    /// Returns the socket family of the socket address.
30    pub fn from_socket_addr(addr: &SocketAddr) -> Self {
31        match addr {
32            SocketAddr::V4(_) => SocketFamily::IPV4,
33            SocketAddr::V6(_) => SocketFamily::IPV6,
34        }
35    }
36
37    /// Returns true if the socket family is IPv4.
38    pub fn is_v4(&self) -> bool {
39        matches!(self, SocketFamily::IPV4)
40    }
41
42    /// Returns true if the socket family is IPv6.
43    pub fn is_v6(&self) -> bool {
44        matches!(self, SocketFamily::IPV6)
45    }
46
47    /// Converts the socket family to a `socket2::Domain`.
48    pub(crate) fn to_domain(&self) -> socket2::Domain {
49        match self {
50            SocketFamily::IPV4 => socket2::Domain::IPV4,
51            SocketFamily::IPV6 => socket2::Domain::IPV6,
52        }
53    }
54}