use std::net::UdpSocket;
use std::io::Result;
use std::io::Error;
pub enum Domain {
IpV4,
Ipv6
}
mod sealing {
pub trait Unbounded {}
impl Unbounded for std::net::UdpSocket {}
}
pub trait Unbounded : sealing::Unbounded where Self: Sized {
fn unbounded(domain: Domain) -> Result<Self>;
}
impl Unbounded for UdpSocket {
fn unbounded(domain: Domain) -> Result<Self> {
#[cfg(unix)]
{
use std::os::unix::io::FromRawFd;
let domain = match domain {
Domain::IpV4 => libc::AF_INET,
Domain::Ipv6 => libc::AF_INET6
};
let fd = unsafe { libc::socket(domain, libc::SOCK_DGRAM, libc::IPPROTO_UDP) };
if fd == -1 {
return Err(Error::last_os_error());
}
let socket = unsafe { UdpSocket::from_raw_fd(fd) };
Ok(socket)
}
#[cfg(windows)]
{
use std::os::windows::io::FromRawSocket;
use std::os::windows::io::RawSocket;
use windows_sys::Win32::Networking::WinSock::SOCK_DGRAM;
use windows_sys::Win32::Networking::WinSock::IPPROTO_UDP;
use windows_sys::Win32::Networking::WinSock::AF_INET;
use windows_sys::Win32::Networking::WinSock::AF_INET6;
use windows_sys::Win32::Networking::WinSock::socket;
use windows_sys::Win32::Networking::WinSock::WSAGetLastError;
use windows_sys::Win32::Networking::WinSock::INVALID_SOCKET;
let domain = match domain {
Domain::IpV4 => AF_INET,
Domain::Ipv6 => AF_INET6
};
let sock = unsafe { socket(domain, SOCK_DGRAM, IPPROTO_UDP) };
if sock == INVALID_SOCKET {
return Err(Error::from_raw_os_error(unsafe { WSAGetLastError() }));
}
let socket = unsafe { UdpSocket::from_raw_socket(sock as RawSocket) };
Ok(socket)
}
}
}