• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 use std::io;
2 use std::net::{self, SocketAddr};
3 use std::os::windows::io::AsRawSocket;
4 
5 use windows_sys::Win32::Networking::WinSock::{self, SOCKET, SOCKET_ERROR, SOCK_STREAM};
6 
7 use crate::sys::windows::net::{new_ip_socket, socket_addr};
8 
new_for_addr(address: SocketAddr) -> io::Result<SOCKET>9 pub(crate) fn new_for_addr(address: SocketAddr) -> io::Result<SOCKET> {
10     new_ip_socket(address, SOCK_STREAM)
11 }
12 
bind(socket: &net::TcpListener, addr: SocketAddr) -> io::Result<()>13 pub(crate) fn bind(socket: &net::TcpListener, addr: SocketAddr) -> io::Result<()> {
14     use WinSock::bind;
15 
16     let (raw_addr, raw_addr_length) = socket_addr(&addr);
17     syscall!(
18         bind(
19             socket.as_raw_socket() as _,
20             raw_addr.as_ptr(),
21             raw_addr_length
22         ),
23         PartialEq::eq,
24         SOCKET_ERROR
25     )?;
26     Ok(())
27 }
28 
connect(socket: &net::TcpStream, addr: SocketAddr) -> io::Result<()>29 pub(crate) fn connect(socket: &net::TcpStream, addr: SocketAddr) -> io::Result<()> {
30     use WinSock::connect;
31 
32     let (raw_addr, raw_addr_length) = socket_addr(&addr);
33     let res = syscall!(
34         connect(
35             socket.as_raw_socket() as _,
36             raw_addr.as_ptr(),
37             raw_addr_length
38         ),
39         PartialEq::eq,
40         SOCKET_ERROR
41     );
42 
43     match res {
44         Err(err) if err.kind() != io::ErrorKind::WouldBlock => Err(err),
45         _ => Ok(()),
46     }
47 }
48 
listen(socket: &net::TcpListener, backlog: u32) -> io::Result<()>49 pub(crate) fn listen(socket: &net::TcpListener, backlog: u32) -> io::Result<()> {
50     use std::convert::TryInto;
51     use WinSock::listen;
52 
53     let backlog = backlog.try_into().unwrap_or(i32::max_value());
54     syscall!(
55         listen(socket.as_raw_socket() as _, backlog),
56         PartialEq::eq,
57         SOCKET_ERROR
58     )?;
59     Ok(())
60 }
61 
accept(listener: &net::TcpListener) -> io::Result<(net::TcpStream, SocketAddr)>62 pub(crate) fn accept(listener: &net::TcpListener) -> io::Result<(net::TcpStream, SocketAddr)> {
63     // The non-blocking state of `listener` is inherited. See
64     // https://docs.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-accept#remarks.
65     listener.accept()
66 }
67