Skip to content

Commit

Permalink
bugfix: Initialize networking on Windows
Browse files Browse the repository at this point in the history
This commit adds a setup_networking function. On most platforms it does
nothing. However, on Windows it calls `wsa_startup`. This ensures that
all networking is set up before anything else is called.

Closes #182
  • Loading branch information
notgull authored Jan 27, 2024
1 parent d4218b8 commit adf46bb
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 0 deletions.
16 changes: 16 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2069,6 +2069,8 @@ fn connect(
#[cfg(windows)]
use rustix::fd::AsFd;

setup_networking();

#[cfg(any(
target_os = "android",
target_os = "dragonfly",
Expand Down Expand Up @@ -2168,6 +2170,20 @@ fn connect(
Ok(socket)
}

#[inline]
fn setup_networking() {
#[cfg(windows)]
{
// On Windows, we need to call WSAStartup before calling any networking code.
// Make sure to call it at least once.
static INIT: std::sync::Once = std::sync::Once::new();

INIT.call_once(|| {
let _ = rustix::net::wsa_startup();
});
}
}

#[inline]
fn set_nonblocking(
#[cfg(unix)] fd: BorrowedFd<'_>,
Expand Down
18 changes: 18 additions & 0 deletions tests/issue_182.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
//! https://github.com/smol-rs/async-io/issues/182

use async_io::Async;
use std::net::{TcpStream, ToSocketAddrs};

#[test]
fn networking_initialized() {
let address = match ToSocketAddrs::to_socket_addrs(&("google.com", 80)) {
Ok(mut addrs) => addrs.next().unwrap(),
Err(err) => {
eprintln!("Got error {err} when looking up google.com, exiting test early.");
return;
}
};
async_io::block_on(async move {
let _ = Async::<TcpStream>::connect(address).await.unwrap();
});
}

0 comments on commit adf46bb

Please sign in to comment.