1mod async_impl;
2mod sync_impl;
3
4use nex_packet::ip::IpNextLevelProtocol;
5use socket2::{Domain, Type};
6
7use crate::sys;
8
9pub use async_impl::*;
10pub use sync_impl::*;
11
12#[derive(Clone, Debug)]
14pub enum IpVersion {
15 V4,
16 V6,
17}
18
19impl IpVersion {
20 pub fn version_u8(&self) -> u8 {
22 match self {
23 IpVersion::V4 => 4,
24 IpVersion::V6 => 6,
25 }
26 }
27 pub fn is_ipv4(&self) -> bool {
29 match self {
30 IpVersion::V4 => true,
31 IpVersion::V6 => false,
32 }
33 }
34 pub fn is_ipv6(&self) -> bool {
36 match self {
37 IpVersion::V4 => false,
38 IpVersion::V6 => true,
39 }
40 }
41 pub(crate) fn to_domain(&self) -> Domain {
42 match self {
43 IpVersion::V4 => Domain::IPV4,
44 IpVersion::V6 => Domain::IPV6,
45 }
46 }
47}
48
49#[derive(Clone, Debug)]
51pub enum SocketType {
52 Raw,
54 Datagram,
56 Stream,
58}
59
60impl SocketType {
61 pub(crate) fn to_type(&self) -> Type {
62 match self {
63 SocketType::Raw => Type::RAW,
64 SocketType::Datagram => Type::DGRAM,
65 SocketType::Stream => Type::STREAM,
66 }
67 }
68 pub(crate) fn from_type(t: Type) -> SocketType {
69 match t {
70 Type::RAW => SocketType::Raw,
71 Type::DGRAM => SocketType::Datagram,
72 Type::STREAM => SocketType::Stream,
73 _ => SocketType::Stream,
74 }
75 }
76}
77
78#[derive(Clone, Debug)]
80pub struct SocketOption {
81 pub ip_version: IpVersion,
83 pub socket_type: SocketType,
85 pub protocol: Option<IpNextLevelProtocol>,
87 pub non_blocking: bool,
89}
90
91impl SocketOption {
92 pub fn new(
94 ip_version: IpVersion,
95 socket_type: SocketType,
96 protocol: Option<IpNextLevelProtocol>,
97 ) -> SocketOption {
98 SocketOption {
99 ip_version,
100 socket_type,
101 protocol,
102 non_blocking: false,
103 }
104 }
105 pub fn is_valid(&self) -> Result<(), String> {
108 sys::check_socket_option(self.clone())
109 }
110}
111
112fn to_socket_protocol(protocol: IpNextLevelProtocol) -> socket2::Protocol {
113 match protocol {
114 IpNextLevelProtocol::Tcp => socket2::Protocol::TCP,
115 IpNextLevelProtocol::Udp => socket2::Protocol::UDP,
116 IpNextLevelProtocol::Icmp => socket2::Protocol::ICMPV4,
117 IpNextLevelProtocol::Icmpv6 => socket2::Protocol::ICMPV6,
118 _ => socket2::Protocol::TCP,
119 }
120}