Skip to content

Commit adf46bb

Browse files
authored
bugfix: Initialize networking on Windows
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
1 parent d4218b8 commit adf46bb

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed

src/lib.rs

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2069,6 +2069,8 @@ fn connect(
20692069
#[cfg(windows)]
20702070
use rustix::fd::AsFd;
20712071

2072+
setup_networking();
2073+
20722074
#[cfg(any(
20732075
target_os = "android",
20742076
target_os = "dragonfly",
@@ -2168,6 +2170,20 @@ fn connect(
21682170
Ok(socket)
21692171
}
21702172

2173+
#[inline]
2174+
fn setup_networking() {
2175+
#[cfg(windows)]
2176+
{
2177+
// On Windows, we need to call WSAStartup before calling any networking code.
2178+
// Make sure to call it at least once.
2179+
static INIT: std::sync::Once = std::sync::Once::new();
2180+
2181+
INIT.call_once(|| {
2182+
let _ = rustix::net::wsa_startup();
2183+
});
2184+
}
2185+
}
2186+
21712187
#[inline]
21722188
fn set_nonblocking(
21732189
#[cfg(unix)] fd: BorrowedFd<'_>,

tests/issue_182.rs

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
//! https://github.com/smol-rs/async-io/issues/182
2+
3+
use async_io::Async;
4+
use std::net::{TcpStream, ToSocketAddrs};
5+
6+
#[test]
7+
fn networking_initialized() {
8+
let address = match ToSocketAddrs::to_socket_addrs(&("google.com", 80)) {
9+
Ok(mut addrs) => addrs.next().unwrap(),
10+
Err(err) => {
11+
eprintln!("Got error {err} when looking up google.com, exiting test early.");
12+
return;
13+
}
14+
};
15+
async_io::block_on(async move {
16+
let _ = Async::<TcpStream>::connect(address).await.unwrap();
17+
});
18+
}

0 commit comments

Comments
 (0)