Skip to main content

nex_socket/
lib.rs

1//! Cross-platform low-level socket APIs for TCP, UDP and ICMP.
2//!
3//! `nex-socket` focuses on predictable, low-level behavior and platform-aware
4//! socket option control.
5
6pub mod icmp;
7pub mod tcp;
8pub mod udp;
9
10use std::net::{IpAddr, SocketAddr};
11
12/// Represents the socket address family (IPv4 or IPv6)
13#[derive(Debug, Clone, Copy, PartialEq, Eq)]
14pub enum SocketFamily {
15    IPV4,
16    IPV6,
17}
18
19impl SocketFamily {
20    /// Returns the socket family of the IP address.
21    pub fn from_ip(ip: &IpAddr) -> Self {
22        match ip {
23            IpAddr::V4(_) => SocketFamily::IPV4,
24            IpAddr::V6(_) => SocketFamily::IPV6,
25        }
26    }
27
28    /// Returns the socket family of the socket address.
29    pub fn from_socket_addr(addr: &SocketAddr) -> Self {
30        match addr {
31            SocketAddr::V4(_) => SocketFamily::IPV4,
32            SocketAddr::V6(_) => SocketFamily::IPV6,
33        }
34    }
35
36    /// Returns true if the socket family is IPv4.
37    pub fn is_v4(&self) -> bool {
38        matches!(self, SocketFamily::IPV4)
39    }
40
41    /// Returns true if the socket family is IPv6.
42    pub fn is_v6(&self) -> bool {
43        matches!(self, SocketFamily::IPV6)
44    }
45
46    /// Converts the socket family to a `socket2::Domain`.
47    pub(crate) fn to_domain(&self) -> socket2::Domain {
48        match self {
49            SocketFamily::IPV4 => socket2::Domain::IPV4,
50            SocketFamily::IPV6 => socket2::Domain::IPV6,
51        }
52    }
53}