mproxy_socket_dispatch/
lib.rs

1//! MPROXY: Socket Dispatcher. Platform-agnostic API to bind unicast and multicast UDP socket addresses.
2//! Provides socket interface for crates `mproxy-client`, `mproxy-server`, `mproxy-proxy`, and `mproxy-reverseproxy`.
3
4use std::io;
5use std::net::SocketAddr;
6
7pub use socket2::{Domain, Protocol, Socket, Type};
8
9pub const BUFSIZE: usize = 8192;
10
11#[cfg(unix)]
12pub fn bind_socket(socket: &Socket, addr: &SocketAddr) -> io::Result<()> {
13    socket.bind(&socket2::SockAddr::from(*addr))
14}
15
16/// https://msdn.microsoft.com/en-us/library/windows/desktop/ms737550(v=vs.85).aspx
17#[cfg(windows)]
18use std::net::{Ipv4Addr, Ipv6Addr};
19#[cfg(windows)]
20pub fn bind_socket(socket: &Socket, addr: &SocketAddr) -> io::Result<()> {
21    let addr = match addr.ip().is_multicast() {
22        true => match addr {
23            SocketAddr::V4(addr) => SocketAddr::new(Ipv4Addr::new(0, 0, 0, 0).into(), addr.port()),
24            SocketAddr::V6(addr) => {
25                SocketAddr::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0).into(), addr.port())
26            }
27        },
28        false => *addr,
29    };
30    socket.bind(&socket2::SockAddr::from(addr))
31}
32
33pub fn new_socket(addr: &SocketAddr) -> io::Result<Socket> {
34    let domain = if addr.is_ipv4() {
35        Domain::IPV4
36    } else if addr.is_ipv6() {
37        Domain::IPV6
38    } else {
39        #[cfg(windows)]
40        panic!();
41        #[cfg(unix)]
42        Domain::UNIX
43    };
44
45    let socket = Socket::new(domain, Type::DGRAM, Some(Protocol::UDP))?;
46
47    #[cfg(unix)]
48    if let Err(e) = socket.set_reuse_port(true) {
49        eprintln!(
50            "Could not set reusable port! This feature requires unix. {}",
51            e
52        );
53    }
54    #[cfg(target_os = "linux")]
55    if let Err(e) = socket.set_freebind(true) {
56        eprintln!(
57            "Could not set freebind socket! This feature requires linux. {}",
58            e
59        );
60    }
61    socket.set_read_timeout(None)?;
62    Ok(socket)
63}