Commit 34891b528e

Andrew Kelley <andrew@ziglang.org>
2025-10-20 20:12:08
std.Io.Threaded: implement netListen for Windows
1 parent 62c0496
Changed files (6)
lib/std/Io/Threaded.zig
@@ -4,6 +4,7 @@ const builtin = @import("builtin");
 const native_os = builtin.os.tag;
 const is_windows = native_os == .windows;
 const windows = std.os.windows;
+const ws2_32 = std.os.windows.ws2_32;
 
 const std = @import("../std.zig");
 const Io = std.Io;
@@ -24,6 +25,7 @@ threads: std.ArrayListUnmanaged(std.Thread),
 stack_size: usize,
 cpu_count: std.Thread.CpuCountError!usize,
 concurrent_count: usize,
+wsa: if (is_windows) Wsa else struct {} = .{},
 
 threadlocal var current_closure: ?*Closure = null;
 
@@ -105,6 +107,9 @@ pub fn deinit(t: *Threaded) void {
     const gpa = t.allocator;
     t.join();
     t.threads.deinit(gpa);
+    if (is_windows and t.wsa.status == .initialized) {
+        if (ws2_32.WSACleanup() != 0) recoverableOsBugDetected();
+    }
     t.* = undefined;
 }
 
@@ -234,7 +239,7 @@ pub fn io(t: *Threaded) Io {
             },
 
             .netListenIp = switch (builtin.os.tag) {
-                .windows => @panic("TODO"),
+                .windows => netListenIpWindows,
                 else => netListenIpPosix,
             },
             .netListenUnix = netListenUnix,
@@ -2797,6 +2802,116 @@ fn netListenIpPosix(
     };
 }
 
+fn netListenIpWindows(
+    userdata: ?*anyopaque,
+    address: IpAddress,
+    options: IpAddress.ListenOptions,
+) IpAddress.ListenError!net.Server {
+    if (!have_networking) return error.NetworkDown;
+    const t: *Threaded = @ptrCast(@alignCast(userdata));
+    const family = posixAddressFamily(&address);
+    const mode = posixSocketMode(options.mode);
+    const protocol = posixProtocol(options.protocol);
+
+    const socket_handle = while (true) {
+        try t.checkCancel();
+        const flags: u32 = ws2_32.WSA_FLAG_OVERLAPPED | ws2_32.WSA_FLAG_NO_HANDLE_INHERIT;
+        const rc = ws2_32.WSASocketW(family, @bitCast(mode), @bitCast(protocol), null, 0, flags);
+        if (rc != ws2_32.INVALID_SOCKET) break rc;
+        switch (ws2_32.WSAGetLastError()) {
+            .EINTR => continue,
+            .ECANCELLED, .E_CANCELLED => return error.Canceled,
+            .NOTINITIALISED => {
+                try initializeWsa(t);
+                continue;
+            },
+            .EAFNOSUPPORT => return error.AddressFamilyUnsupported,
+            .EMFILE => return error.ProcessFdQuotaExceeded,
+            .ENOBUFS => return error.SystemResources,
+            .EPROTONOSUPPORT => return error.ProtocolUnsupportedBySystem,
+            else => |err| return windows.unexpectedWSAError(err),
+        }
+    };
+    errdefer closeSocketWindows(socket_handle);
+
+    if (options.reuse_address)
+        try setSocketOptionWsa(t, socket_handle, posix.SOL.SOCKET, posix.SO.REUSEADDR, 1);
+
+    var storage: WsaAddress = undefined;
+    var addr_len = addressToWsa(&address, &storage);
+
+    while (true) {
+        try t.checkCancel();
+        const rc = ws2_32.bind(socket_handle, &storage.any, addr_len);
+        if (rc != ws2_32.SOCKET_ERROR) break;
+        switch (ws2_32.WSAGetLastError()) {
+            .EINTR => continue,
+            .ECANCELLED, .E_CANCELLED => return error.Canceled,
+            .NOTINITIALISED => {
+                try initializeWsa(t);
+                continue;
+            },
+            .EADDRINUSE => return error.AddressInUse,
+            .EADDRNOTAVAIL => return error.AddressUnavailable,
+            .ENOTSOCK => |err| return wsaErrorBug(err),
+            .EFAULT => |err| return wsaErrorBug(err),
+            .EINVAL => |err| return wsaErrorBug(err),
+            .ENOBUFS => return error.SystemResources,
+            .ENETDOWN => return error.NetworkDown,
+            else => |err| return windows.unexpectedWSAError(err),
+        }
+    }
+
+    while (true) {
+        try t.checkCancel();
+        const rc = ws2_32.listen(socket_handle, options.kernel_backlog);
+        if (rc != ws2_32.SOCKET_ERROR) break;
+        switch (ws2_32.WSAGetLastError()) {
+            .EINTR => continue,
+            .ECANCELLED, .E_CANCELLED => return error.Canceled,
+            .NOTINITIALISED => {
+                try initializeWsa(t);
+                continue;
+            },
+            .ENETDOWN => return error.NetworkDown,
+            .EADDRINUSE => return error.AddressInUse,
+            .EISCONN => |err| return wsaErrorBug(err),
+            .EINVAL => |err| return wsaErrorBug(err),
+            .EMFILE, .ENOBUFS => return error.SystemResources,
+            .ENOTSOCK => |err| return wsaErrorBug(err),
+            .EOPNOTSUPP => |err| return wsaErrorBug(err),
+            .EINPROGRESS => |err| return wsaErrorBug(err),
+            else => |err| return windows.unexpectedWSAError(err),
+        }
+    }
+
+    while (true) {
+        try t.checkCancel();
+        const rc = ws2_32.getsockname(socket_handle, &storage.any, &addr_len);
+        if (rc != ws2_32.SOCKET_ERROR) break;
+        switch (ws2_32.WSAGetLastError()) {
+            .EINTR => continue,
+            .ECANCELLED, .E_CANCELLED => return error.Canceled,
+            .NOTINITIALISED => {
+                try initializeWsa(t);
+                continue;
+            },
+            .ENETDOWN => return error.NetworkDown,
+            .EFAULT => |err| return wsaErrorBug(err),
+            .ENOTSOCK => |err| return wsaErrorBug(err),
+            .EINVAL => |err| return wsaErrorBug(err),
+            else => |err| return windows.unexpectedWSAError(err),
+        }
+    }
+
+    return .{
+        .socket = .{
+            .handle = socket_handle,
+            .address = addressFromWsa(&storage),
+        },
+    };
+}
+
 fn netListenUnix(
     userdata: ?*anyopaque,
     address: *const net.UnixAddress,
@@ -2971,7 +3086,7 @@ fn setSocketOption(t: *Threaded, fd: posix.fd_t, level: i32, opt_name: u32, opti
             .CANCELED => return error.Canceled,
 
             .BADF => |err| return errnoBug(err), // File descriptor used after closed.
-            .NOTSOCK => |err| return errnoBug(err), // always a race condition
+            .NOTSOCK => |err| return errnoBug(err),
             .INVAL => |err| return errnoBug(err),
             .FAULT => |err| return errnoBug(err),
             else => |err| return posix.unexpectedErrno(err),
@@ -2979,6 +3094,27 @@ fn setSocketOption(t: *Threaded, fd: posix.fd_t, level: i32, opt_name: u32, opti
     }
 }
 
+fn setSocketOptionWsa(t: *Threaded, socket: Io.net.Socket.Handle, level: i32, opt_name: u32, option: u32) !void {
+    const o: []const u8 = @ptrCast(&option);
+    const rc = ws2_32.setsockopt(socket, level, @bitCast(opt_name), o.ptr, @intCast(o.len));
+    while (true) {
+        if (rc != ws2_32.SOCKET_ERROR) return;
+        switch (ws2_32.WSAGetLastError()) {
+            .EINTR => continue,
+            .ECANCELLED, .E_CANCELLED => return error.Canceled,
+            .NOTINITIALISED => {
+                try initializeWsa(t);
+                continue;
+            },
+            .ENETDOWN => return error.NetworkDown,
+            .EFAULT => |err| return wsaErrorBug(err),
+            .ENOTSOCK => |err| return wsaErrorBug(err),
+            .EINVAL => |err| return wsaErrorBug(err),
+            else => |err| return windows.unexpectedWSAError(err),
+        }
+    }
+}
+
 fn netConnectIpPosix(
     userdata: ?*anyopaque,
     address: *const IpAddress,
@@ -3263,25 +3399,31 @@ fn netSendOne(
         try t.checkCancel();
         const rc = posix.system.sendmsg(handle, &msg, flags);
         if (is_windows) {
-            if (rc == windows.ws2_32.SOCKET_ERROR) {
-                switch (windows.ws2_32.WSAGetLastError()) {
-                    .WSAEACCES => return error.AccessDenied,
-                    .WSAEADDRNOTAVAIL => return error.AddressNotAvailable,
-                    .WSAECONNRESET => return error.ConnectionResetByPeer,
-                    .WSAEMSGSIZE => return error.MessageOversize,
-                    .WSAENOBUFS => return error.SystemResources,
-                    .WSAENOTSOCK => return error.FileDescriptorNotASocket,
-                    .WSAEAFNOSUPPORT => return error.AddressFamilyUnsupported,
-                    .WSAEDESTADDRREQ => unreachable, // A destination address is required.
-                    .WSAEFAULT => unreachable, // The lpBuffers, lpTo, lpOverlapped, lpNumberOfBytesSent, or lpCompletionRoutine parameters are not part of the user address space, or the lpTo parameter is too small.
-                    .WSAEHOSTUNREACH => return error.NetworkUnreachable,
-                    .WSAEINVAL => unreachable,
-                    .WSAENETDOWN => return error.NetworkDown,
-                    .WSAENETRESET => return error.ConnectionResetByPeer,
-                    .WSAENETUNREACH => return error.NetworkUnreachable,
-                    .WSAENOTCONN => return error.SocketUnconnected,
-                    .WSAESHUTDOWN => unreachable, // The socket has been shut down; it is not possible to WSASendTo on a socket after shutdown has been invoked with how set to SD_SEND or SD_BOTH.
-                    .WSANOTINITIALISED => unreachable, // A successful WSAStartup call must occur before using this function.
+            if (rc == ws2_32.SOCKET_ERROR) {
+                switch (ws2_32.WSAGetLastError()) {
+                    .EINTR => continue,
+                    .ECANCELLED, .E_CANCELLED => return error.Canceled,
+                    .NOTINITIALISED => {
+                        try initializeWsa(t);
+                        continue;
+                    },
+                    .EACCES => return error.AccessDenied,
+                    .EADDRNOTAVAIL => return error.AddressUnavailable,
+                    .ECONNRESET => return error.ConnectionResetByPeer,
+                    .EMSGSIZE => return error.MessageOversize,
+                    .ENOBUFS => return error.SystemResources,
+                    .ENOTSOCK => return error.FileDescriptorNotASocket,
+                    .EAFNOSUPPORT => return error.AddressFamilyUnsupported,
+                    .EDESTADDRREQ => unreachable, // A destination address is required.
+                    .EFAULT => unreachable, // The lpBuffers, lpTo, lpOverlapped, lpNumberOfBytesSent, or lpCompletionRoutine parameters are not part of the user address space, or the lpTo parameter is too small.
+                    .EHOSTUNREACH => return error.NetworkUnreachable,
+                    .EINVAL => unreachable,
+                    .ENETDOWN => return error.NetworkDown,
+                    .ENETRESET => return error.ConnectionResetByPeer,
+                    .ENETUNREACH => return error.NetworkUnreachable,
+                    .ENOTCONN => return error.SocketUnconnected,
+                    .ESHUTDOWN => unreachable, // The socket has been shut down; it is not possible to WSASendTo on a socket after shutdown has been invoked with how set to SD_SEND or SD_BOTH.
+                    .NOTINITIALISED => unreachable, // A successful WSAStartup call must occur before using this function.
                     else => |err| return windows.unexpectedWSAError(err),
                 }
             } else {
@@ -3613,7 +3755,7 @@ fn netClose(userdata: ?*anyopaque, handle: net.Socket.Handle) void {
     const t: *Threaded = @ptrCast(@alignCast(userdata));
     _ = t;
     switch (native_os) {
-        .windows => windows.closesocket(handle) catch recoverableOsBugDetected(),
+        .windows => closeSocketWindows(handle) catch recoverableOsBugDetected(),
         else => posix.close(handle),
     }
 }
@@ -3664,7 +3806,7 @@ fn netInterfaceNameResolve(
 
     if (native_os == .windows) {
         try t.checkCancel();
-        const index = windows.ws2_32.if_nametoindex(&name.bytes);
+        const index = ws2_32.if_nametoindex(&name.bytes);
         if (index == 0) return error.InterfaceNotFound;
         return .{ .index = index };
     }
@@ -3881,6 +4023,13 @@ const UnixAddress = extern union {
     un: posix.sockaddr.un,
 };
 
+const WsaAddress = extern union {
+    any: ws2_32.sockaddr,
+    in: ws2_32.sockaddr.in,
+    in6: ws2_32.sockaddr.in6,
+    un: ws2_32.sockaddr.un,
+};
+
 fn posixAddressFamily(a: *const IpAddress) posix.sa_family_t {
     return switch (a.*) {
         .ip4 => posix.AF.INET,
@@ -3896,6 +4045,14 @@ fn addressFromPosix(posix_address: *const PosixAddress) IpAddress {
     };
 }
 
+fn addressFromWsa(wsa_address: *const WsaAddress) IpAddress {
+    return switch (wsa_address.any.family) {
+        posix.AF.INET => .{ .ip4 = address4FromWsa(&wsa_address.in) },
+        posix.AF.INET6 => .{ .ip6 = address6FromWsa(&wsa_address.in6) },
+        else => .{ .ip4 = .loopback(0) },
+    };
+}
+
 fn addressToPosix(a: *const IpAddress, storage: *PosixAddress) posix.socklen_t {
     return switch (a.*) {
         .ip4 => |ip4| {
@@ -3909,6 +4066,19 @@ fn addressToPosix(a: *const IpAddress, storage: *PosixAddress) posix.socklen_t {
     };
 }
 
+fn addressToWsa(a: *const IpAddress, storage: *WsaAddress) i32 {
+    return switch (a.*) {
+        .ip4 => |ip4| {
+            storage.in = address4ToPosix(ip4);
+            return @sizeOf(posix.sockaddr.in);
+        },
+        .ip6 => |*ip6| {
+            storage.in6 = address6ToPosix(ip6);
+            return @sizeOf(posix.sockaddr.in6);
+        },
+    };
+}
+
 fn addressUnixToPosix(a: *const net.UnixAddress, storage: *UnixAddress) posix.socklen_t {
     @memcpy(storage.un.path[0..a.path.len], a.path);
     storage.un.family = posix.AF.UNIX;
@@ -3932,6 +4102,22 @@ fn address6FromPosix(in6: *const posix.sockaddr.in6) net.Ip6Address {
     };
 }
 
+fn address4FromWsa(in: *const ws2_32.sockaddr.in) net.Ip4Address {
+    return .{
+        .port = std.mem.bigToNative(u16, in.port),
+        .bytes = @bitCast(in.addr),
+    };
+}
+
+fn address6FromWsa(in6: *const ws2_32.sockaddr.in6) net.Ip6Address {
+    return .{
+        .port = std.mem.bigToNative(u16, in6.port),
+        .bytes = in6.addr,
+        .flow = in6.flowinfo,
+        .interface = .{ .index = in6.scope_id },
+    };
+}
+
 fn address4ToPosix(a: net.Ip4Address) posix.sockaddr.in {
     return .{
         .port = std.mem.nativeToBig(u16, a.port),
@@ -3955,6 +4141,13 @@ fn errnoBug(err: posix.E) Io.UnexpectedError {
     }
 }
 
+fn wsaErrorBug(err: ws2_32.WinsockError) Io.UnexpectedError {
+    switch (builtin.mode) {
+        .Debug => std.debug.panic("programmer bug caused syscall error: {t}", .{err}),
+        else => return error.Unexpected,
+    }
+}
+
 fn posixSocketMode(mode: net.Socket.Mode) u32 {
     return switch (mode) {
         .stream => posix.SOCK.STREAM,
@@ -4814,3 +5007,59 @@ pub const ResetEvent = enum(u32) {
         @atomicStore(ResetEvent, re, .unset, .monotonic);
     }
 };
+
+fn closeSocketWindows(s: ws2_32.SOCKET) void {
+    const rc = ws2_32.closesocket(s);
+    if (builtin.mode == .Debug) switch (rc) {
+        0 => {},
+        ws2_32.SOCKET_ERROR => switch (ws2_32.WSAGetLastError()) {
+            else => unreachable,
+        },
+        else => unreachable,
+    };
+}
+
+const Wsa = struct {
+    status: Status = .uninitialized,
+    mutex: Io.Mutex = .init,
+    init_error: ?Wsa.InitError = null,
+
+    const Status = enum { uninitialized, initialized, failure };
+
+    const InitError = error{
+        ProcessFdQuotaExceeded,
+        NetworkDown,
+        VersionUnsupported,
+        BlockingOperationInProgress,
+    } || Io.UnexpectedError;
+};
+
+fn initializeWsa(t: *Threaded) error{NetworkDown}!void {
+    const t_io = t.io();
+    const wsa = &t.wsa;
+    wsa.mutex.lockUncancelable(t_io);
+    defer wsa.mutex.unlock(t_io);
+    switch (wsa.status) {
+        .uninitialized => {
+            var wsa_data: ws2_32.WSADATA = undefined;
+            const minor_version = 2;
+            const major_version = 2;
+            switch (ws2_32.WSAStartup((@as(windows.WORD, minor_version) << 8) | major_version, &wsa_data)) {
+                0 => {
+                    wsa.status = .initialized;
+                    return;
+                },
+                else => |err_int| switch (@as(ws2_32.WinsockError, @enumFromInt(@as(u16, @intCast(err_int))))) {
+                    .SYSNOTREADY => wsa.init_error = error.NetworkDown,
+                    .VERNOTSUPPORTED => wsa.init_error = error.VersionUnsupported,
+                    .EINPROGRESS => wsa.init_error = error.BlockingOperationInProgress,
+                    .EPROCLIM => wsa.init_error = error.ProcessFdQuotaExceeded,
+                    else => |err| wsa.init_error = windows.unexpectedWSAError(err),
+                },
+            }
+        },
+        .initialized => return,
+        .failure => {},
+    }
+    return error.NetworkDown;
+}
lib/std/os/windows/test.zig
@@ -237,28 +237,3 @@ test "removeDotDirs" {
     try testRemoveDotDirs("a\\b\\..\\", "a\\");
     try testRemoveDotDirs("a\\b\\..\\c", "a\\c");
 }
-
-test "loadWinsockExtensionFunction" {
-    _ = try windows.WSAStartup(2, 2);
-    defer windows.WSACleanup() catch unreachable;
-
-    const LPFN_CONNECTEX = *const fn (
-        Socket: windows.ws2_32.SOCKET,
-        SockAddr: *const windows.ws2_32.sockaddr,
-        SockLen: std.posix.socklen_t,
-        SendBuf: ?*const anyopaque,
-        SendBufLen: windows.DWORD,
-        BytesSent: *windows.DWORD,
-        Overlapped: *windows.OVERLAPPED,
-    ) callconv(.winapi) windows.BOOL;
-
-    _ = windows.loadWinsockExtensionFunction(
-        LPFN_CONNECTEX,
-        try std.posix.socket(std.posix.AF.INET, std.posix.SOCK.DGRAM, 0),
-        windows.ws2_32.WSAID_CONNECTEX,
-    ) catch |err| switch (err) {
-        error.OperationNotSupported => unreachable,
-        error.ShortRead => unreachable,
-        else => |e| return e,
-    };
-}
lib/std/os/windows/ws2_32.zig
@@ -1271,130 +1271,105 @@ pub const timeval = extern struct {
     usec: LONG,
 };
 
-// https://docs.microsoft.com/en-au/windows/win32/winsock/windows-sockets-error-codes-2
+/// https://docs.microsoft.com/en-au/windows/win32/winsock/windows-sockets-error-codes-2
 pub const WinsockError = enum(u16) {
     /// Specified event object handle is invalid.
     /// An application attempts to use an event object, but the specified handle is not valid.
-    WSA_INVALID_HANDLE = 6,
-
+    INVALID_HANDLE = 6,
     /// Insufficient memory available.
     /// An application used a Windows Sockets function that directly maps to a Windows function.
     /// The Windows function is indicating a lack of required memory resources.
-    WSA_NOT_ENOUGH_MEMORY = 8,
-
+    NOT_ENOUGH_MEMORY = 8,
     /// One or more parameters are invalid.
     /// An application used a Windows Sockets function which directly maps to a Windows function.
     /// The Windows function is indicating a problem with one or more parameters.
-    WSA_INVALID_PARAMETER = 87,
-
+    INVALID_PARAMETER = 87,
     /// Overlapped operation aborted.
     /// An overlapped operation was canceled due to the closure of the socket, or the execution of the SIO_FLUSH command in WSAIoctl.
-    WSA_OPERATION_ABORTED = 995,
-
+    OPERATION_ABORTED = 995,
     /// Overlapped I/O event object not in signaled state.
     /// The application has tried to determine the status of an overlapped operation which is not yet completed.
     /// Applications that use WSAGetOverlappedResult (with the fWait flag set to FALSE) in a polling mode to determine when an overlapped operation has completed, get this error code until the operation is complete.
-    WSA_IO_INCOMPLETE = 996,
-
+    IO_INCOMPLETE = 996,
     /// The application has initiated an overlapped operation that cannot be completed immediately.
     /// A completion indication will be given later when the operation has been completed.
-    WSA_IO_PENDING = 997,
-
+    IO_PENDING = 997,
     /// Interrupted function call.
     /// A blocking operation was interrupted by a call to WSACancelBlockingCall.
-    WSAEINTR = 10004,
-
+    EINTR = 10004,
     /// File handle is not valid.
     /// The file handle supplied is not valid.
-    WSAEBADF = 10009,
-
+    EBADF = 10009,
     /// Permission denied.
     /// An attempt was made to access a socket in a way forbidden by its access permissions.
     /// An example is using a broadcast address for sendto without broadcast permission being set using setsockopt(SO.BROADCAST).
     /// Another possible reason for the WSAEACCES error is that when the bind function is called (on Windows NT 4.0 with SP4 and later), another application, service, or kernel mode driver is bound to the same address with exclusive access.
     /// Such exclusive access is a new feature of Windows NT 4.0 with SP4 and later, and is implemented by using the SO.EXCLUSIVEADDRUSE option.
-    WSAEACCES = 10013,
-
+    EACCES = 10013,
     /// Bad address.
     /// The system detected an invalid pointer address in attempting to use a pointer argument of a call.
     /// This error occurs if an application passes an invalid pointer value, or if the length of the buffer is too small.
     /// For instance, if the length of an argument, which is a sockaddr structure, is smaller than the sizeof(sockaddr).
-    WSAEFAULT = 10014,
-
+    EFAULT = 10014,
     /// Invalid argument.
     /// Some invalid argument was supplied (for example, specifying an invalid level to the setsockopt function).
     /// In some instances, it also refers to the current state of the socketโ€”for instance, calling accept on a socket that is not listening.
-    WSAEINVAL = 10022,
-
+    EINVAL = 10022,
     /// Too many open files.
     /// Too many open sockets. Each implementation may have a maximum number of socket handles available, either globally, per process, or per thread.
-    WSAEMFILE = 10024,
-
+    EMFILE = 10024,
     /// Resource temporarily unavailable.
     /// This error is returned from operations on nonblocking sockets that cannot be completed immediately, for example recv when no data is queued to be read from the socket.
     /// It is a nonfatal error, and the operation should be retried later.
     /// It is normal for WSAEWOULDBLOCK to be reported as the result from calling connect on a nonblocking SOCK.STREAM socket, since some time must elapse for the connection to be established.
-    WSAEWOULDBLOCK = 10035,
-
+    EWOULDBLOCK = 10035,
     /// Operation now in progress.
     /// A blocking operation is currently executing.
     /// Windows Sockets only allows a single blocking operationโ€”per- task or threadโ€”to be outstanding, and if any other function call is made (whether or not it references that or any other socket) the function fails with the WSAEINPROGRESS error.
-    WSAEINPROGRESS = 10036,
-
+    EINPROGRESS = 10036,
     /// Operation already in progress.
     /// An operation was attempted on a nonblocking socket with an operation already in progressโ€”that is, calling connect a second time on a nonblocking socket that is already connecting, or canceling an asynchronous request (WSAAsyncGetXbyY) that has already been canceled or completed.
-    WSAEALREADY = 10037,
-
+    EALREADY = 10037,
     /// Socket operation on nonsocket.
     /// An operation was attempted on something that is not a socket.
     /// Either the socket handle parameter did not reference a valid socket, or for select, a member of an fd_set was not valid.
-    WSAENOTSOCK = 10038,
-
+    ENOTSOCK = 10038,
     /// Destination address required.
     /// A required address was omitted from an operation on a socket.
     /// For example, this error is returned if sendto is called with the remote address of ADDR_ANY.
-    WSAEDESTADDRREQ = 10039,
-
+    EDESTADDRREQ = 10039,
     /// Message too long.
     /// A message sent on a datagram socket was larger than the internal message buffer or some other network limit, or the buffer used to receive a datagram was smaller than the datagram itself.
-    WSAEMSGSIZE = 10040,
-
+    EMSGSIZE = 10040,
     /// Protocol wrong type for socket.
     /// A protocol was specified in the socket function call that does not support the semantics of the socket type requested.
     /// For example, the ARPA Internet UDP protocol cannot be specified with a socket type of SOCK.STREAM.
-    WSAEPROTOTYPE = 10041,
-
+    EPROTOTYPE = 10041,
     /// Bad protocol option.
     /// An unknown, invalid or unsupported option or level was specified in a getsockopt or setsockopt call.
-    WSAENOPROTOOPT = 10042,
-
+    ENOPROTOOPT = 10042,
     /// Protocol not supported.
     /// The requested protocol has not been configured into the system, or no implementation for it exists.
     /// For example, a socket call requests a SOCK.DGRAM socket, but specifies a stream protocol.
-    WSAEPROTONOSUPPORT = 10043,
-
+    EPROTONOSUPPORT = 10043,
     /// Socket type not supported.
     /// The support for the specified socket type does not exist in this address family.
     /// For example, the optional type SOCK.RAW might be selected in a socket call, and the implementation does not support SOCK.RAW sockets at all.
-    WSAESOCKTNOSUPPORT = 10044,
-
+    ESOCKTNOSUPPORT = 10044,
     /// Operation not supported.
     /// The attempted operation is not supported for the type of object referenced.
     /// Usually this occurs when a socket descriptor to a socket that cannot support this operation is trying to accept a connection on a datagram socket.
-    WSAEOPNOTSUPP = 10045,
-
+    EOPNOTSUPP = 10045,
     /// Protocol family not supported.
     /// The protocol family has not been configured into the system or no implementation for it exists.
     /// This message has a slightly different meaning from WSAEAFNOSUPPORT.
     /// However, it is interchangeable in most cases, and all Windows Sockets functions that return one of these messages also specify WSAEAFNOSUPPORT.
-    WSAEPFNOSUPPORT = 10046,
-
+    EPFNOSUPPORT = 10046,
     /// Address family not supported by protocol family.
     /// An address incompatible with the requested protocol was used.
     /// All sockets are created with an associated address family (that is, AF.INET for Internet Protocols) and a generic protocol type (that is, SOCK.STREAM).
     /// This error is returned if an incorrect protocol is explicitly requested in the socket call, or if an address of the wrong family is used for a socket, for example, in sendto.
-    WSAEAFNOSUPPORT = 10047,
-
+    EAFNOSUPPORT = 10047,
     /// Address already in use.
     /// Typically, only one usage of each socket address (protocol/IP address/port) is permitted.
     /// This error occurs if an application attempts to bind a socket to an IP address/port that has already been used for an existing socket, or a socket that was not closed properly, or one that is still in the process of closing.
@@ -1402,115 +1377,91 @@ pub const WinsockError = enum(u16) {
     /// Client applications usually need not call bind at allโ€”connect chooses an unused port automatically.
     /// When bind is called with a wildcard address (involving ADDR_ANY), a WSAEADDRINUSE error could be delayed until the specific address is committed.
     /// This could happen with a call to another function later, including connect, listen, WSAConnect, or WSAJoinLeaf.
-    WSAEADDRINUSE = 10048,
-
+    EADDRINUSE = 10048,
     /// Cannot assign requested address.
     /// The requested address is not valid in its context.
     /// This normally results from an attempt to bind to an address that is not valid for the local computer.
     /// This can also result from connect, sendto, WSAConnect, WSAJoinLeaf, or WSASendTo when the remote address or port is not valid for a remote computer (for example, address or port 0).
-    WSAEADDRNOTAVAIL = 10049,
-
+    EADDRNOTAVAIL = 10049,
     /// Network is down.
     /// A socket operation encountered a dead network.
     /// This could indicate a serious failure of the network system (that is, the protocol stack that the Windows Sockets DLL runs over), the network interface, or the local network itself.
-    WSAENETDOWN = 10050,
-
+    ENETDOWN = 10050,
     /// Network is unreachable.
     /// A socket operation was attempted to an unreachable network.
     /// This usually means the local software knows no route to reach the remote host.
-    WSAENETUNREACH = 10051,
-
+    ENETUNREACH = 10051,
     /// Network dropped connection on reset.
     /// The connection has been broken due to keep-alive activity detecting a failure while the operation was in progress.
     /// It can also be returned by setsockopt if an attempt is made to set SO.KEEPALIVE on a connection that has already failed.
-    WSAENETRESET = 10052,
-
+    ENETRESET = 10052,
     /// Software caused connection abort.
     /// An established connection was aborted by the software in your host computer, possibly due to a data transmission time-out or protocol error.
-    WSAECONNABORTED = 10053,
-
+    ECONNABORTED = 10053,
     /// Connection reset by peer.
     /// An existing connection was forcibly closed by the remote host.
     /// This normally results if the peer application on the remote host is suddenly stopped, the host is rebooted, the host or remote network interface is disabled, or the remote host uses a hard close (see setsockopt for more information on the SO.LINGER option on the remote socket).
     /// This error may also result if a connection was broken due to keep-alive activity detecting a failure while one or more operations are in progress.
     /// Operations that were in progress fail with WSAENETRESET. Subsequent operations fail with WSAECONNRESET.
-    WSAECONNRESET = 10054,
-
+    ECONNRESET = 10054,
     /// No buffer space available.
     /// An operation on a socket could not be performed because the system lacked sufficient buffer space or because a queue was full.
-    WSAENOBUFS = 10055,
-
+    ENOBUFS = 10055,
     /// Socket is already connected.
     /// A connect request was made on an already-connected socket.
     /// Some implementations also return this error if sendto is called on a connected SOCK.DGRAM socket (for SOCK.STREAM sockets, the to parameter in sendto is ignored) although other implementations treat this as a legal occurrence.
-    WSAEISCONN = 10056,
-
+    EISCONN = 10056,
     /// Socket is not connected.
     /// A request to send or receive data was disallowed because the socket is not connected and (when sending on a datagram socket using sendto) no address was supplied.
     /// Any other type of operation might also return this errorโ€”for example, setsockopt setting SO.KEEPALIVE if the connection has been reset.
-    WSAENOTCONN = 10057,
-
+    ENOTCONN = 10057,
     /// Cannot send after socket shutdown.
     /// A request to send or receive data was disallowed because the socket had already been shut down in that direction with a previous shutdown call.
     /// By calling shutdown a partial close of a socket is requested, which is a signal that sending or receiving, or both have been discontinued.
-    WSAESHUTDOWN = 10058,
-
+    ESHUTDOWN = 10058,
     /// Too many references.
     /// Too many references to some kernel object.
-    WSAETOOMANYREFS = 10059,
-
+    ETOOMANYREFS = 10059,
     /// Connection timed out.
     /// A connection attempt failed because the connected party did not properly respond after a period of time, or the established connection failed because the connected host has failed to respond.
-    WSAETIMEDOUT = 10060,
-
+    ETIMEDOUT = 10060,
     /// Connection refused.
     /// No connection could be made because the target computer actively refused it.
     /// This usually results from trying to connect to a service that is inactive on the foreign hostโ€”that is, one with no server application running.
-    WSAECONNREFUSED = 10061,
-
+    ECONNREFUSED = 10061,
     /// Cannot translate name.
     /// Cannot translate a name.
-    WSAELOOP = 10062,
-
+    ELOOP = 10062,
     /// Name too long.
     /// A name component or a name was too long.
-    WSAENAMETOOLONG = 10063,
-
+    ENAMETOOLONG = 10063,
     /// Host is down.
     /// A socket operation failed because the destination host is down. A socket operation encountered a dead host.
     /// Networking activity on the local host has not been initiated.
     /// These conditions are more likely to be indicated by the error WSAETIMEDOUT.
-    WSAEHOSTDOWN = 10064,
-
+    EHOSTDOWN = 10064,
     /// No route to host.
     /// A socket operation was attempted to an unreachable host. See WSAENETUNREACH.
-    WSAEHOSTUNREACH = 10065,
-
+    EHOSTUNREACH = 10065,
     /// Directory not empty.
     /// Cannot remove a directory that is not empty.
-    WSAENOTEMPTY = 10066,
-
+    ENOTEMPTY = 10066,
     /// Too many processes.
     /// A Windows Sockets implementation may have a limit on the number of applications that can use it simultaneously.
     /// WSAStartup may fail with this error if the limit has been reached.
-    WSAEPROCLIM = 10067,
-
+    EPROCLIM = 10067,
     /// User quota exceeded.
     /// Ran out of user quota.
-    WSAEUSERS = 10068,
-
+    EUSERS = 10068,
     /// Disk quota exceeded.
     /// Ran out of disk quota.
-    WSAEDQUOT = 10069,
-
+    EDQUOT = 10069,
     /// Stale file handle reference.
     /// The file handle reference is no longer available.
-    WSAESTALE = 10070,
-
+    ESTALE = 10070,
     /// Item is remote.
     /// The item is not available locally.
-    WSAEREMOTE = 10071,
-
+    EREMOTE = 10071,
     /// Network subsystem is unavailable.
     /// This error is returned by WSAStartup if the Windows Sockets implementation cannot function at this time because the underlying system it uses to provide network services is currently unavailable.
     /// Users should check:
@@ -1518,47 +1469,38 @@ pub const WinsockError = enum(u16) {
     ///   - That they are not trying to use more than one Windows Sockets implementation simultaneously.
     ///   - If there is more than one Winsock DLL on your system, be sure the first one in the path is appropriate for the network subsystem currently loaded.
     ///   - The Windows Sockets implementation documentation to be sure all necessary components are currently installed and configured correctly.
-    WSASYSNOTREADY = 10091,
-
+    SYSNOTREADY = 10091,
     /// Winsock.dll version out of range.
     /// The current Windows Sockets implementation does not support the Windows Sockets specification version requested by the application.
     /// Check that no old Windows Sockets DLL files are being accessed.
-    WSAVERNOTSUPPORTED = 10092,
-
+    VERNOTSUPPORTED = 10092,
     /// Successful WSAStartup not yet performed.
     /// Either the application has not called WSAStartup or WSAStartup failed.
     /// The application may be accessing a socket that the current active task does not own (that is, trying to share a socket between tasks), or WSACleanup has been called too many times.
-    WSANOTINITIALISED = 10093,
-
+    NOTINITIALISED = 10093,
     /// Graceful shutdown in progress.
     /// Returned by WSARecv and WSARecvFrom to indicate that the remote party has initiated a graceful shutdown sequence.
-    WSAEDISCON = 10101,
-
+    EDISCON = 10101,
     /// No more results.
     /// No more results can be returned by the WSALookupServiceNext function.
-    WSAENOMORE = 10102,
-
+    ENOMORE = 10102,
     /// Call has been canceled.
     /// A call to the WSALookupServiceEnd function was made while this call was still processing. The call has been canceled.
-    WSAECANCELLED = 10103,
-
+    ECANCELLED = 10103,
     /// Procedure call table is invalid.
     /// The service provider procedure call table is invalid.
     /// A service provider returned a bogus procedure table to Ws2_32.dll.
     /// This is usually caused by one or more of the function pointers being NULL.
-    WSAEINVALIDPROCTABLE = 10104,
-
+    EINVALIDPROCTABLE = 10104,
     /// Service provider is invalid.
     /// The requested service provider is invalid.
     /// This error is returned by the WSCGetProviderInfo and WSCGetProviderInfo32 functions if the protocol entry specified could not be found.
     /// This error is also returned if the service provider returned a version number other than 2.0.
-    WSAEINVALIDPROVIDER = 10105,
-
+    EINVALIDPROVIDER = 10105,
     /// Service provider failed to initialize.
     /// The requested service provider could not be loaded or initialized.
     /// This error is returned if either a service provider's DLL could not be loaded (LoadLibrary failed) or the provider's WSPStartup or NSPStartup function failed.
-    WSAEPROVIDERFAILEDINIT = 10106,
-
+    EPROVIDERFAILEDINIT = 10106,
     /// System call failure.
     /// A system call that should never fail has failed.
     /// This is a generic error code, returned under various conditions.
@@ -1566,157 +1508,120 @@ pub const WinsockError = enum(u16) {
     /// For example, if a call to WaitForMultipleEvents fails or one of the registry functions fails trying to manipulate the protocol/namespace catalogs.
     /// Returned when a provider does not return SUCCESS and does not provide an extended error code.
     /// Can indicate a service provider implementation error.
-    WSASYSCALLFAILURE = 10107,
-
+    SYSCALLFAILURE = 10107,
     /// Service not found.
     /// No such service is known. The service cannot be found in the specified name space.
-    WSASERVICE_NOT_FOUND = 10108,
-
+    SERVICE_NOT_FOUND = 10108,
     /// Class type not found.
     /// The specified class was not found.
-    WSATYPE_NOT_FOUND = 10109,
-
+    TYPE_NOT_FOUND = 10109,
     /// No more results.
     /// No more results can be returned by the WSALookupServiceNext function.
-    WSA_E_NO_MORE = 10110,
-
+    E_NO_MORE = 10110,
     /// Call was canceled.
     /// A call to the WSALookupServiceEnd function was made while this call was still processing. The call has been canceled.
-    WSA_E_CANCELLED = 10111,
-
+    E_CANCELLED = 10111,
     /// Database query was refused.
     /// A database query failed because it was actively refused.
-    WSAEREFUSED = 10112,
-
+    EREFUSED = 10112,
     /// Host not found.
     /// No such host is known. The name is not an official host name or alias, or it cannot be found in the database(s) being queried.
     /// This error may also be returned for protocol and service queries, and means that the specified name could not be found in the relevant database.
-    WSAHOST_NOT_FOUND = 11001,
-
+    HOST_NOT_FOUND = 11001,
     /// Nonauthoritative host not found.
     /// This is usually a temporary error during host name resolution and means that the local server did not receive a response from an authoritative server. A retry at some time later may be successful.
-    WSATRY_AGAIN = 11002,
-
+    TRY_AGAIN = 11002,
     /// This is a nonrecoverable error.
     /// This indicates that some sort of nonrecoverable error occurred during a database lookup.
     /// This may be because the database files (for example, BSD-compatible HOSTS, SERVICES, or PROTOCOLS files) could not be found, or a DNS request was returned by the server with a severe error.
-    WSANO_RECOVERY = 11003,
-
+    NO_RECOVERY = 11003,
     /// Valid name, no data record of requested type.
     /// The requested name is valid and was found in the database, but it does not have the correct associated data being resolved for.
     /// The usual example for this is a host name-to-address translation attempt (using gethostbyname or WSAAsyncGetHostByName) which uses the DNS (Domain Name Server).
     /// An MX record is returned but no A recordโ€”indicating the host itself exists, but is not directly reachable.
-    WSANO_DATA = 11004,
-
+    NO_DATA = 11004,
     /// QoS receivers.
     /// At least one QoS reserve has arrived.
-    WSA_QOS_RECEIVERS = 11005,
-
+    QOS_RECEIVERS = 11005,
     /// QoS senders.
     /// At least one QoS send path has arrived.
-    WSA_QOS_SENDERS = 11006,
-
+    QOS_SENDERS = 11006,
     /// No QoS senders.
     /// There are no QoS senders.
-    WSA_QOS_NO_SENDERS = 11007,
-
+    QOS_NO_SENDERS = 11007,
     /// QoS no receivers.
     /// There are no QoS receivers.
-    WSA_QOS_NO_RECEIVERS = 11008,
-
+    QOS_NO_RECEIVERS = 11008,
     /// QoS request confirmed.
     /// The QoS reserve request has been confirmed.
-    WSA_QOS_REQUEST_CONFIRMED = 11009,
-
+    QOS_REQUEST_CONFIRMED = 11009,
     /// QoS admission error.
     /// A QoS error occurred due to lack of resources.
-    WSA_QOS_ADMISSION_FAILURE = 11010,
-
+    QOS_ADMISSION_FAILURE = 11010,
     /// QoS policy failure.
     /// The QoS request was rejected because the policy system couldn't allocate the requested resource within the existing policy.
-    WSA_QOS_POLICY_FAILURE = 11011,
-
+    QOS_POLICY_FAILURE = 11011,
     /// QoS bad style.
     /// An unknown or conflicting QoS style was encountered.
-    WSA_QOS_BAD_STYLE = 11012,
-
+    QOS_BAD_STYLE = 11012,
     /// QoS bad object.
     /// A problem was encountered with some part of the filterspec or the provider-specific buffer in general.
-    WSA_QOS_BAD_OBJECT = 11013,
-
+    QOS_BAD_OBJECT = 11013,
     /// QoS traffic control error.
     /// An error with the underlying traffic control (TC) API as the generic QoS request was converted for local enforcement by the TC API.
     /// This could be due to an out of memory error or to an internal QoS provider error.
-    WSA_QOS_TRAFFIC_CTRL_ERROR = 11014,
-
+    QOS_TRAFFIC_CTRL_ERROR = 11014,
     /// QoS generic error.
     /// A general QoS error.
-    WSA_QOS_GENERIC_ERROR = 11015,
-
+    QOS_GENERIC_ERROR = 11015,
     /// QoS service type error.
     /// An invalid or unrecognized service type was found in the QoS flowspec.
-    WSA_QOS_ESERVICETYPE = 11016,
-
+    QOS_ESERVICETYPE = 11016,
     /// QoS flowspec error.
     /// An invalid or inconsistent flowspec was found in the QOS structure.
-    WSA_QOS_EFLOWSPEC = 11017,
-
+    QOS_EFLOWSPEC = 11017,
     /// Invalid QoS provider buffer.
     /// An invalid QoS provider-specific buffer.
-    WSA_QOS_EPROVSPECBUF = 11018,
-
+    QOS_EPROVSPECBUF = 11018,
     /// Invalid QoS filter style.
     /// An invalid QoS filter style was used.
-    WSA_QOS_EFILTERSTYLE = 11019,
-
+    QOS_EFILTERSTYLE = 11019,
     /// Invalid QoS filter type.
     /// An invalid QoS filter type was used.
-    WSA_QOS_EFILTERTYPE = 11020,
-
+    QOS_EFILTERTYPE = 11020,
     /// Incorrect QoS filter count.
     /// An incorrect number of QoS FILTERSPECs were specified in the FLOWDESCRIPTOR.
-    WSA_QOS_EFILTERCOUNT = 11021,
-
+    QOS_EFILTERCOUNT = 11021,
     /// Invalid QoS object length.
     /// An object with an invalid ObjectLength field was specified in the QoS provider-specific buffer.
-    WSA_QOS_EOBJLENGTH = 11022,
-
+    QOS_EOBJLENGTH = 11022,
     /// Incorrect QoS flow count.
     /// An incorrect number of flow descriptors was specified in the QoS structure.
-    WSA_QOS_EFLOWCOUNT = 11023,
-
+    QOS_EFLOWCOUNT = 11023,
     /// Unrecognized QoS object.
     /// An unrecognized object was found in the QoS provider-specific buffer.
-    WSA_QOS_EUNKOWNPSOBJ = 11024,
-
+    QOS_EUNKOWNPSOBJ = 11024,
     /// Invalid QoS policy object.
     /// An invalid policy object was found in the QoS provider-specific buffer.
-    WSA_QOS_EPOLICYOBJ = 11025,
-
+    QOS_EPOLICYOBJ = 11025,
     /// Invalid QoS flow descriptor.
     /// An invalid QoS flow descriptor was found in the flow descriptor list.
-    WSA_QOS_EFLOWDESC = 11026,
-
+    QOS_EFLOWDESC = 11026,
     /// Invalid QoS provider-specific flowspec.
     /// An invalid or inconsistent flowspec was found in the QoS provider-specific buffer.
-    WSA_QOS_EPSFLOWSPEC = 11027,
-
+    QOS_EPSFLOWSPEC = 11027,
     /// Invalid QoS provider-specific filterspec.
     /// An invalid FILTERSPEC was found in the QoS provider-specific buffer.
-    WSA_QOS_EPSFILTERSPEC = 11028,
-
+    QOS_EPSFILTERSPEC = 11028,
     /// Invalid QoS shape discard mode object.
     /// An invalid shape discard mode object was found in the QoS provider-specific buffer.
-    WSA_QOS_ESDMODEOBJ = 11029,
-
+    QOS_ESDMODEOBJ = 11029,
     /// Invalid QoS shaping rate object.
     /// An invalid shaping rate object was found in the QoS provider-specific buffer.
-    WSA_QOS_ESHAPERATEOBJ = 11030,
-
+    QOS_ESHAPERATEOBJ = 11030,
     /// Reserved policy QoS element type.
     /// A reserved policy element was found in the QoS provider-specific buffer.
-    WSA_QOS_RESERVED_PETYPE = 11031,
-
+    QOS_RESERVED_PETYPE = 11031,
     _,
 };
 
lib/std/os/windows.zig
@@ -1574,131 +1574,11 @@ pub fn GetFileAttributesW(lpFileName: [*:0]const u16) GetFileAttributesError!DWO
     return rc;
 }
 
-pub fn WSAStartup(majorVersion: u8, minorVersion: u8) !ws2_32.WSADATA {
-    var wsadata: ws2_32.WSADATA = undefined;
-    return switch (ws2_32.WSAStartup((@as(WORD, minorVersion) << 8) | majorVersion, &wsadata)) {
-        0 => wsadata,
-        else => |err_int| switch (@as(ws2_32.WinsockError, @enumFromInt(@as(u16, @intCast(err_int))))) {
-            .WSASYSNOTREADY => return error.SystemNotAvailable,
-            .WSAVERNOTSUPPORTED => return error.VersionNotSupported,
-            .WSAEINPROGRESS => return error.BlockingOperationInProgress,
-            .WSAEPROCLIM => return error.ProcessFdQuotaExceeded,
-            else => |err| return unexpectedWSAError(err),
-        },
-    };
-}
-
-pub fn WSACleanup() !void {
-    return switch (ws2_32.WSACleanup()) {
-        0 => {},
-        ws2_32.SOCKET_ERROR => switch (ws2_32.WSAGetLastError()) {
-            .WSANOTINITIALISED => return error.NotInitialized,
-            .WSAENETDOWN => return error.NetworkNotAvailable,
-            .WSAEINPROGRESS => return error.BlockingOperationInProgress,
-            else => |err| return unexpectedWSAError(err),
-        },
-        else => unreachable,
-    };
-}
-
-var wsa_startup_mutex: std.Thread.Mutex = .{};
-
-pub fn callWSAStartup() !void {
-    wsa_startup_mutex.lock();
-    defer wsa_startup_mutex.unlock();
-
-    // Here we could use a flag to prevent multiple threads to prevent
-    // multiple calls to WSAStartup, but it doesn't matter. We're globally
-    // leaking the resource intentionally, and the mutex already prevents
-    // data races within the WSAStartup function.
-    _ = WSAStartup(2, 2) catch |err| switch (err) {
-        error.SystemNotAvailable => return error.SystemResources,
-        error.VersionNotSupported => return error.Unexpected,
-        error.BlockingOperationInProgress => return error.Unexpected,
-        error.ProcessFdQuotaExceeded => return error.ProcessFdQuotaExceeded,
-        error.Unexpected => return error.Unexpected,
-    };
-}
-
-/// Microsoft requires WSAStartup to be called to initialize, or else
-/// WSASocketW will return WSANOTINITIALISED.
-/// Since this is a standard library, we do not have the luxury of
-/// putting initialization code anywhere, because we would not want
-/// to pay the cost of calling WSAStartup if there ended up being no
-/// networking. Also, if Zig code is used as a library, Zig is not in
-/// charge of the start code, and we couldn't put in any initialization
-/// code even if we wanted to.
-/// The documentation for WSAStartup mentions that there must be a
-/// matching WSACleanup call. It is not possible for the Zig Standard
-/// Library to honor this for the same reason - there is nowhere to put
-/// deinitialization code.
-/// So, API users of the zig std lib have two options:
-///  * (recommended) The simple, cross-platform way: just call `WSASocketW`
-///    and don't worry about it. Zig will call WSAStartup() in a thread-safe
-///    manner and never deinitialize networking. This is ideal for an
-///    application which has the capability to do networking.
-///  * The getting-your-hands-dirty way: call `WSAStartup()` before doing
-///    networking, so that the error handling code for WSANOTINITIALISED never
-///    gets run, which then allows the application or library to call `WSACleanup()`.
-///    This could make sense for a library, which has init and deinit
-///    functions for the whole library's lifetime.
-pub fn WSASocketW(
-    af: i32,
-    socket_type: i32,
-    protocol: i32,
-    protocolInfo: ?*ws2_32.WSAPROTOCOL_INFOW,
-    g: ws2_32.GROUP,
-    dwFlags: DWORD,
-) !ws2_32.SOCKET {
-    var first = true;
-    while (true) {
-        const rc = ws2_32.WSASocketW(af, socket_type, protocol, protocolInfo, g, dwFlags);
-        if (rc == ws2_32.INVALID_SOCKET) {
-            switch (ws2_32.WSAGetLastError()) {
-                .WSAEAFNOSUPPORT => return error.AddressFamilyUnsupported,
-                .WSAEMFILE => return error.ProcessFdQuotaExceeded,
-                .WSAENOBUFS => return error.SystemResources,
-                .WSAEPROTONOSUPPORT => return error.ProtocolNotSupported,
-                .WSANOTINITIALISED => {
-                    if (!first) return error.Unexpected;
-                    first = false;
-                    try callWSAStartup();
-                    continue;
-                },
-                else => |err| return unexpectedWSAError(err),
-            }
-        }
-        return rc;
-    }
-}
-
-pub fn bind(s: ws2_32.SOCKET, name: *const ws2_32.sockaddr, namelen: ws2_32.socklen_t) i32 {
-    return ws2_32.bind(s, name, @as(i32, @intCast(namelen)));
-}
-
-pub fn listen(s: ws2_32.SOCKET, backlog: u31) i32 {
-    return ws2_32.listen(s, backlog);
-}
-
-pub fn closesocket(s: ws2_32.SOCKET) !void {
-    switch (ws2_32.closesocket(s)) {
-        0 => {},
-        ws2_32.SOCKET_ERROR => switch (ws2_32.WSAGetLastError()) {
-            else => |err| return unexpectedWSAError(err),
-        },
-        else => unreachable,
-    }
-}
-
 pub fn accept(s: ws2_32.SOCKET, name: ?*ws2_32.sockaddr, namelen: ?*ws2_32.socklen_t) ws2_32.SOCKET {
     assert((name == null) == (namelen == null));
     return ws2_32.accept(s, name, @as(?*i32, @ptrCast(namelen)));
 }
 
-pub fn getsockname(s: ws2_32.SOCKET, name: *ws2_32.sockaddr, namelen: *ws2_32.socklen_t) i32 {
-    return ws2_32.getsockname(s, name, @as(*i32, @ptrCast(namelen)));
-}
-
 pub fn getpeername(s: ws2_32.SOCKET, name: *ws2_32.sockaddr, namelen: *ws2_32.socklen_t) i32 {
     return ws2_32.getpeername(s, name, @as(*i32, @ptrCast(namelen)));
 }
@@ -2816,38 +2696,6 @@ inline fn MAKELANGID(p: c_ushort, s: c_ushort) LANGID {
     return (s << 10) | p;
 }
 
-/// Loads a Winsock extension function in runtime specified by a GUID.
-pub fn loadWinsockExtensionFunction(comptime T: type, sock: ws2_32.SOCKET, guid: GUID) !T {
-    var function: T = undefined;
-    var num_bytes: DWORD = undefined;
-
-    const rc = ws2_32.WSAIoctl(
-        sock,
-        ws2_32.SIO_GET_EXTENSION_FUNCTION_POINTER,
-        &guid,
-        @sizeOf(GUID),
-        @as(?*anyopaque, @ptrFromInt(@intFromPtr(&function))),
-        @sizeOf(T),
-        &num_bytes,
-        null,
-        null,
-    );
-
-    if (rc == ws2_32.SOCKET_ERROR) {
-        return switch (ws2_32.WSAGetLastError()) {
-            .WSAEOPNOTSUPP => error.OperationNotSupported,
-            .WSAENOTSOCK => error.FileDescriptorNotASocket,
-            else => |err| unexpectedWSAError(err),
-        };
-    }
-
-    if (num_bytes != @sizeOf(T)) {
-        return error.ShortRead;
-    }
-
-    return function;
-}
-
 /// Call this when you made a windows DLL call or something that does SetLastError
 /// and you get an unexpected error.
 pub fn unexpectedError(err: Win32Error) UnexpectedError {
lib/std/posix/test.zig
@@ -520,25 +520,6 @@ test "getrlimit and setrlimit" {
     }
 }
 
-test "shutdown socket" {
-    if (native_os == .wasi)
-        return error.SkipZigTest;
-    if (native_os == .windows) {
-        _ = try std.os.windows.WSAStartup(2, 2);
-    }
-    defer {
-        if (native_os == .windows) {
-            std.os.windows.WSACleanup() catch unreachable;
-        }
-    }
-    const sock = try posix.socket(posix.AF.INET, posix.SOCK.STREAM, 0);
-    posix.shutdown(sock, .both) catch |err| switch (err) {
-        error.SocketUnconnected => {},
-        else => |e| return e,
-    };
-    std.posix.close(sock);
-}
-
 test "sigrtmin/max" {
     if (native_os == .wasi or native_os == .windows or native_os == .macos) {
         return error.SkipZigTest;
lib/std/posix.zig
@@ -3290,33 +3290,6 @@ pub const SocketError = error{
 } || UnexpectedError;
 
 pub fn socket(domain: u32, socket_type: u32, protocol: u32) SocketError!socket_t {
-    if (native_os == .windows) {
-        // These flags are not actually part of the Windows API, instead they are converted here for compatibility
-        const filtered_sock_type = socket_type & ~@as(u32, SOCK.NONBLOCK | SOCK.CLOEXEC);
-        var flags: u32 = windows.ws2_32.WSA_FLAG_OVERLAPPED;
-        if ((socket_type & SOCK.CLOEXEC) != 0) flags |= windows.ws2_32.WSA_FLAG_NO_HANDLE_INHERIT;
-
-        const rc = try windows.WSASocketW(
-            @bitCast(domain),
-            @bitCast(filtered_sock_type),
-            @bitCast(protocol),
-            null,
-            0,
-            flags,
-        );
-        errdefer windows.closesocket(rc) catch unreachable;
-        if ((socket_type & SOCK.NONBLOCK) != 0) {
-            var mode: c_ulong = 1; // nonblocking
-            if (windows.ws2_32.SOCKET_ERROR == windows.ws2_32.ioctlsocket(rc, windows.ws2_32.FIONBIO, &mode)) {
-                switch (windows.ws2_32.WSAGetLastError()) {
-                    // have not identified any error codes that should be handled yet
-                    else => unreachable,
-                }
-            }
-        }
-        return rc;
-    }
-
     const have_sock_flags = !builtin.target.os.tag.isDarwin() and native_os != .haiku;
     const filtered_sock_type = if (!have_sock_flags)
         socket_type & ~@as(u32, SOCK.NONBLOCK | SOCK.CLOEXEC)
@@ -3411,14 +3384,14 @@ pub fn shutdown(sock: socket_t, how: ShutdownHow) ShutdownError!void {
             .both => windows.ws2_32.SD_BOTH,
         });
         if (0 != result) switch (windows.ws2_32.WSAGetLastError()) {
-            .WSAECONNABORTED => return error.ConnectionAborted,
-            .WSAECONNRESET => return error.ConnectionResetByPeer,
-            .WSAEINPROGRESS => return error.BlockingOperationInProgress,
-            .WSAEINVAL => unreachable,
-            .WSAENETDOWN => return error.NetworkDown,
-            .WSAENOTCONN => return error.SocketUnconnected,
-            .WSAENOTSOCK => unreachable,
-            .WSANOTINITIALISED => unreachable,
+            .ECONNABORTED => return error.ConnectionAborted,
+            .ECONNRESET => return error.ConnectionResetByPeer,
+            .EINPROGRESS => return error.BlockingOperationInProgress,
+            .EINVAL => unreachable,
+            .ENETDOWN => return error.NetworkDown,
+            .ENOTCONN => return error.SocketUnconnected,
+            .ENOTSOCK => unreachable,
+            .NOTINITIALISED => unreachable,
             else => |err| return windows.unexpectedWSAError(err),
         };
     } else {
@@ -3440,70 +3413,17 @@ pub fn shutdown(sock: socket_t, how: ShutdownHow) ShutdownError!void {
 }
 
 pub const BindError = error{
-    /// The address is protected, and the user is not the superuser.
-    /// For UNIX domain sockets: Search permission is denied on  a  component
-    /// of  the  path  prefix.
-    AccessDenied,
-
-    /// The given address is already in use, or in the case of Internet domain sockets,
-    /// The  port number was specified as zero in the socket
-    /// address structure, but, upon attempting to bind to  an  ephemeral  port,  it  was
-    /// determined  that  all  port  numbers in the ephemeral port range are currently in
-    /// use.  See the discussion of /proc/sys/net/ipv4/ip_local_port_range ip(7).
-    AddressInUse,
-
-    /// A nonexistent interface was requested or the requested address was not local.
-    AddressNotAvailable,
-
-    /// The address is not valid for the address family of socket.
-    AddressFamilyUnsupported,
-
-    /// Too many symbolic links were encountered in resolving addr.
     SymLinkLoop,
-
-    /// addr is too long.
     NameTooLong,
-
-    /// A component in the directory prefix of the socket pathname does not exist.
     FileNotFound,
-
-    /// Insufficient kernel memory was available.
-    SystemResources,
-
-    /// A component of the path prefix is not a directory.
     NotDir,
-
-    /// The socket inode would reside on a read-only filesystem.
     ReadOnlyFileSystem,
+    AccessDenied,
+} || std.Io.net.IpAddress.BindError;
 
-    /// The network subsystem has failed.
-    NetworkDown,
-
-    FileDescriptorNotASocket,
-
-    AlreadyBound,
-} || UnexpectedError;
-
-/// addr is `*const T` where T is one of the sockaddr
 pub fn bind(sock: socket_t, addr: *const sockaddr, len: socklen_t) BindError!void {
     if (native_os == .windows) {
-        const rc = windows.bind(sock, addr, len);
-        if (rc == windows.ws2_32.SOCKET_ERROR) {
-            switch (windows.ws2_32.WSAGetLastError()) {
-                .WSANOTINITIALISED => unreachable, // not initialized WSA
-                .WSAEACCES => return error.AccessDenied,
-                .WSAEADDRINUSE => return error.AddressInUse,
-                .WSAEADDRNOTAVAIL => return error.AddressNotAvailable,
-                .WSAENOTSOCK => return error.FileDescriptorNotASocket,
-                .WSAEFAULT => unreachable, // invalid pointers
-                .WSAEINVAL => return error.AlreadyBound,
-                .WSAENOBUFS => return error.SystemResources,
-                .WSAENETDOWN => return error.NetworkDown,
-                else => |err| return windows.unexpectedWSAError(err),
-            }
-            unreachable;
-        }
-        return;
+        @compileError("use std.Io instead");
     } else {
         const rc = system.bind(sock, addr, len);
         switch (errno(rc)) {
@@ -3514,7 +3434,7 @@ pub fn bind(sock: socket_t, addr: *const sockaddr, len: socklen_t) BindError!voi
             .INVAL => unreachable, // invalid parameters
             .NOTSOCK => unreachable, // invalid `sockfd`
             .AFNOSUPPORT => return error.AddressFamilyUnsupported,
-            .ADDRNOTAVAIL => return error.AddressNotAvailable,
+            .ADDRNOTAVAIL => return error.AddressUnavailable,
             .FAULT => unreachable, // invalid `addr` pointer
             .LOOP => return error.SymLinkLoop,
             .NAMETOOLONG => return error.NameTooLong,
@@ -3529,51 +3449,13 @@ pub fn bind(sock: socket_t, addr: *const sockaddr, len: socklen_t) BindError!voi
 }
 
 pub const ListenError = error{
-    /// Another socket is already listening on the same port.
-    /// For Internet domain sockets, the  socket referred to by sockfd had not previously
-    /// been bound to an address and, upon attempting to bind it to an ephemeral port, it
-    /// was determined that all port numbers in the ephemeral port range are currently in
-    /// use.  See the discussion of /proc/sys/net/ipv4/ip_local_port_range in ip(7).
-    AddressInUse,
-
-    /// The file descriptor sockfd does not refer to a socket.
     FileDescriptorNotASocket,
-
-    /// The socket is not of a type that supports the listen() operation.
     OperationNotSupported,
-
-    /// The network subsystem has failed.
-    NetworkDown,
-
-    /// Ran out of system resources
-    /// On Windows it can either run out of socket descriptors or buffer space
-    SystemResources,
-
-    /// Already connected
-    AlreadyConnected,
-
-    /// Socket has not been bound yet
-    SocketNotBound,
-} || UnexpectedError;
+} || std.Io.net.IpAddress.ListenError || std.Io.net.UnixAddress.ListenError;
 
 pub fn listen(sock: socket_t, backlog: u31) ListenError!void {
     if (native_os == .windows) {
-        const rc = windows.listen(sock, backlog);
-        if (rc == windows.ws2_32.SOCKET_ERROR) {
-            switch (windows.ws2_32.WSAGetLastError()) {
-                .WSANOTINITIALISED => unreachable, // not initialized WSA
-                .WSAENETDOWN => return error.NetworkDown,
-                .WSAEADDRINUSE => return error.AddressInUse,
-                .WSAEISCONN => return error.AlreadyConnected,
-                .WSAEINVAL => return error.SocketNotBound,
-                .WSAEMFILE, .WSAENOBUFS => return error.SystemResources,
-                .WSAENOTSOCK => return error.FileDescriptorNotASocket,
-                .WSAEOPNOTSUPP => return error.OperationNotSupported,
-                .WSAEINPROGRESS => unreachable,
-                else => |err| return windows.unexpectedWSAError(err),
-            }
-        }
-        return;
+        @compileError("use std.Io instead");
     } else {
         const rc = system.listen(sock, backlog);
         switch (errno(rc)) {
@@ -3630,16 +3512,16 @@ pub fn accept(
         if (native_os == .windows) {
             if (rc == windows.ws2_32.INVALID_SOCKET) {
                 switch (windows.ws2_32.WSAGetLastError()) {
-                    .WSANOTINITIALISED => unreachable, // not initialized WSA
-                    .WSAECONNRESET => return error.ConnectionResetByPeer,
-                    .WSAEFAULT => unreachable,
-                    .WSAENOTSOCK => return error.FileDescriptorNotASocket,
-                    .WSAEINVAL => return error.SocketNotListening,
-                    .WSAEMFILE => return error.ProcessFdQuotaExceeded,
-                    .WSAENETDOWN => return error.NetworkDown,
-                    .WSAENOBUFS => return error.FileDescriptorNotASocket,
-                    .WSAEOPNOTSUPP => return error.OperationNotSupported,
-                    .WSAEWOULDBLOCK => return error.WouldBlock,
+                    .NOTINITIALISED => unreachable, // not initialized WSA
+                    .ECONNRESET => return error.ConnectionResetByPeer,
+                    .EFAULT => unreachable,
+                    .ENOTSOCK => return error.FileDescriptorNotASocket,
+                    .EINVAL => return error.SocketNotListening,
+                    .EMFILE => return error.ProcessFdQuotaExceeded,
+                    .ENETDOWN => return error.NetworkDown,
+                    .ENOBUFS => return error.FileDescriptorNotASocket,
+                    .EOPNOTSUPP => return error.OperationNotSupported,
+                    .EWOULDBLOCK => return error.WouldBlock,
                     else => |err| return windows.unexpectedWSAError(err),
                 }
             } else {
@@ -3706,9 +3588,9 @@ fn setSockFlags(sock: socket_t, flags: u32) !void {
             var mode: c_ulong = 1;
             if (windows.ws2_32.ioctlsocket(sock, windows.ws2_32.FIONBIO, &mode) == windows.ws2_32.SOCKET_ERROR) {
                 switch (windows.ws2_32.WSAGetLastError()) {
-                    .WSANOTINITIALISED => unreachable,
-                    .WSAENETDOWN => return error.NetworkDown,
-                    .WSAENOTSOCK => return error.FileDescriptorNotASocket,
+                    .NOTINITIALISED => unreachable,
+                    .ENETDOWN => return error.NetworkDown,
+                    .ENOTSOCK => return error.FileDescriptorNotASocket,
                     // TODO: handle more errors
                     else => |err| return windows.unexpectedWSAError(err),
                 }
@@ -3861,11 +3743,11 @@ pub fn getsockname(sock: socket_t, addr: *sockaddr, addrlen: *socklen_t) GetSock
         const rc = windows.getsockname(sock, addr, addrlen);
         if (rc == windows.ws2_32.SOCKET_ERROR) {
             switch (windows.ws2_32.WSAGetLastError()) {
-                .WSANOTINITIALISED => unreachable,
-                .WSAENETDOWN => return error.NetworkDown,
-                .WSAEFAULT => unreachable, // addr or addrlen have invalid pointers or addrlen points to an incorrect value
-                .WSAENOTSOCK => return error.FileDescriptorNotASocket,
-                .WSAEINVAL => return error.SocketNotBound,
+                .NOTINITIALISED => unreachable,
+                .ENETDOWN => return error.NetworkDown,
+                .EFAULT => unreachable, // addr or addrlen have invalid pointers or addrlen points to an incorrect value
+                .ENOTSOCK => return error.FileDescriptorNotASocket,
+                .EINVAL => return error.SocketNotBound,
                 else => |err| return windows.unexpectedWSAError(err),
             }
         }
@@ -3890,11 +3772,11 @@ pub fn getpeername(sock: socket_t, addr: *sockaddr, addrlen: *socklen_t) GetSock
         const rc = windows.getpeername(sock, addr, addrlen);
         if (rc == windows.ws2_32.SOCKET_ERROR) {
             switch (windows.ws2_32.WSAGetLastError()) {
-                .WSANOTINITIALISED => unreachable,
-                .WSAENETDOWN => return error.NetworkDown,
-                .WSAEFAULT => unreachable, // addr or addrlen have invalid pointers or addrlen points to an incorrect value
-                .WSAENOTSOCK => return error.FileDescriptorNotASocket,
-                .WSAEINVAL => return error.SocketNotBound,
+                .NOTINITIALISED => unreachable,
+                .ENETDOWN => return error.NetworkDown,
+                .EFAULT => unreachable, // addr or addrlen have invalid pointers or addrlen points to an incorrect value
+                .ENOTSOCK => return error.FileDescriptorNotASocket,
+                .EINVAL => return error.SocketNotBound,
                 else => |err| return windows.unexpectedWSAError(err),
             }
         }
@@ -3932,7 +3814,7 @@ pub const ConnectError = error{
     /// address and, upon attempting to bind it to an ephemeral port, it was determined that all port numbers
     /// in    the    ephemeral    port    range    are   currently   in   use.    See   the   discussion   of
     /// /proc/sys/net/ipv4/ip_local_port_range in ip(7).
-    AddressNotAvailable,
+    AddressUnavailable,
 
     /// The passed address didn't have the correct address family in its sa_family field.
     AddressFamilyUnsupported,
@@ -3975,22 +3857,22 @@ pub fn connect(sock: socket_t, sock_addr: *const sockaddr, len: socklen_t) Conne
         const rc = windows.ws2_32.connect(sock, sock_addr, @intCast(len));
         if (rc == 0) return;
         switch (windows.ws2_32.WSAGetLastError()) {
-            .WSAEADDRINUSE => return error.AddressInUse,
-            .WSAEADDRNOTAVAIL => return error.AddressNotAvailable,
-            .WSAECONNREFUSED => return error.ConnectionRefused,
-            .WSAECONNRESET => return error.ConnectionResetByPeer,
-            .WSAETIMEDOUT => return error.Timeout,
-            .WSAEHOSTUNREACH, // TODO: should we return NetworkUnreachable in this case as well?
-            .WSAENETUNREACH,
+            .EADDRINUSE => return error.AddressInUse,
+            .EADDRNOTAVAIL => return error.AddressUnavailable,
+            .ECONNREFUSED => return error.ConnectionRefused,
+            .ECONNRESET => return error.ConnectionResetByPeer,
+            .ETIMEDOUT => return error.Timeout,
+            .EHOSTUNREACH, // TODO: should we return NetworkUnreachable in this case as well?
+            .ENETUNREACH,
             => return error.NetworkUnreachable,
-            .WSAEFAULT => unreachable,
-            .WSAEINVAL => unreachable,
-            .WSAEISCONN => return error.AlreadyConnected,
-            .WSAENOTSOCK => unreachable,
-            .WSAEWOULDBLOCK => return error.WouldBlock,
-            .WSAEACCES => unreachable,
-            .WSAENOBUFS => return error.SystemResources,
-            .WSAEAFNOSUPPORT => return error.AddressFamilyUnsupported,
+            .EFAULT => unreachable,
+            .EINVAL => unreachable,
+            .EISCONN => return error.AlreadyConnected,
+            .ENOTSOCK => unreachable,
+            .EWOULDBLOCK => return error.WouldBlock,
+            .EACCES => unreachable,
+            .ENOBUFS => return error.SystemResources,
+            .EAFNOSUPPORT => return error.AddressFamilyUnsupported,
             else => |err| return windows.unexpectedWSAError(err),
         }
         return;
@@ -4002,7 +3884,7 @@ pub fn connect(sock: socket_t, sock_addr: *const sockaddr, len: socklen_t) Conne
             .ACCES => return error.AccessDenied,
             .PERM => return error.PermissionDenied,
             .ADDRINUSE => return error.AddressInUse,
-            .ADDRNOTAVAIL => return error.AddressNotAvailable,
+            .ADDRNOTAVAIL => return error.AddressUnavailable,
             .AFNOSUPPORT => return error.AddressFamilyUnsupported,
             .AGAIN, .INPROGRESS => return error.WouldBlock,
             .ALREADY => return error.ConnectionPending,
@@ -4064,7 +3946,7 @@ pub fn getsockoptError(sockfd: fd_t) ConnectError!void {
             .ACCES => return error.AccessDenied,
             .PERM => return error.PermissionDenied,
             .ADDRINUSE => return error.AddressInUse,
-            .ADDRNOTAVAIL => return error.AddressNotAvailable,
+            .ADDRNOTAVAIL => return error.AddressUnavailable,
             .AFNOSUPPORT => return error.AddressFamilyUnsupported,
             .AGAIN => return error.SystemResources,
             .ALREADY => return error.ConnectionPending,
@@ -5686,7 +5568,7 @@ pub const SendMsgError = SendError || error{
 
     /// The socket is not connected (connection-oriented sockets only).
     SocketUnconnected,
-    AddressNotAvailable,
+    AddressUnavailable,
 };
 
 pub fn sendmsg(
@@ -5701,25 +5583,25 @@ pub fn sendmsg(
         if (native_os == .windows) {
             if (rc == windows.ws2_32.SOCKET_ERROR) {
                 switch (windows.ws2_32.WSAGetLastError()) {
-                    .WSAEACCES => return error.AccessDenied,
-                    .WSAEADDRNOTAVAIL => return error.AddressNotAvailable,
-                    .WSAECONNRESET => return error.ConnectionResetByPeer,
-                    .WSAEMSGSIZE => return error.MessageOversize,
-                    .WSAENOBUFS => return error.SystemResources,
-                    .WSAENOTSOCK => return error.FileDescriptorNotASocket,
-                    .WSAEAFNOSUPPORT => return error.AddressFamilyUnsupported,
-                    .WSAEDESTADDRREQ => unreachable, // A destination address is required.
-                    .WSAEFAULT => unreachable, // The lpBuffers, lpTo, lpOverlapped, lpNumberOfBytesSent, or lpCompletionRoutine parameters are not part of the user address space, or the lpTo parameter is too small.
-                    .WSAEHOSTUNREACH => return error.NetworkUnreachable,
-                    // TODO: WSAEINPROGRESS, WSAEINTR
-                    .WSAEINVAL => unreachable,
-                    .WSAENETDOWN => return error.NetworkDown,
-                    .WSAENETRESET => return error.ConnectionResetByPeer,
-                    .WSAENETUNREACH => return error.NetworkUnreachable,
-                    .WSAENOTCONN => return error.SocketUnconnected,
-                    .WSAESHUTDOWN => unreachable, // The socket has been shut down; it is not possible to WSASendTo on a socket after shutdown has been invoked with how set to SD_SEND or SD_BOTH.
-                    .WSAEWOULDBLOCK => return error.WouldBlock,
-                    .WSANOTINITIALISED => unreachable, // A successful WSAStartup call must occur before using this function.
+                    .EACCES => return error.AccessDenied,
+                    .EADDRNOTAVAIL => return error.AddressUnavailable,
+                    .ECONNRESET => return error.ConnectionResetByPeer,
+                    .EMSGSIZE => return error.MessageOversize,
+                    .ENOBUFS => return error.SystemResources,
+                    .ENOTSOCK => return error.FileDescriptorNotASocket,
+                    .EAFNOSUPPORT => return error.AddressFamilyUnsupported,
+                    .EDESTADDRREQ => unreachable, // A destination address is required.
+                    .EFAULT => unreachable, // The lpBuffers, lpTo, lpOverlapped, lpNumberOfBytesSent, or lpCompletionRoutine parameters are not part of the user address space, or the lpTo parameter is too small.
+                    .EHOSTUNREACH => return error.NetworkUnreachable,
+                    // TODO: EINPROGRESS, EINTR
+                    .EINVAL => unreachable,
+                    .ENETDOWN => return error.NetworkDown,
+                    .ENETRESET => return error.ConnectionResetByPeer,
+                    .ENETUNREACH => return error.NetworkUnreachable,
+                    .ENOTCONN => return error.SocketUnconnected,
+                    .ESHUTDOWN => unreachable, // The socket has been shut down; it is not possible to WSASendTo on a socket after shutdown has been invoked with how set to SD_SEND or SD_BOTH.
+                    .EWOULDBLOCK => return error.WouldBlock,
+                    .NOTINITIALISED => unreachable, // A successful WSAStartup call must occur before using this function.
                     else => |err| return windows.unexpectedWSAError(err),
                 }
             } else {
@@ -5804,25 +5686,25 @@ pub fn sendto(
     if (native_os == .windows) {
         switch (windows.sendto(sockfd, buf.ptr, buf.len, flags, dest_addr, addrlen)) {
             windows.ws2_32.SOCKET_ERROR => switch (windows.ws2_32.WSAGetLastError()) {
-                .WSAEACCES => return error.AccessDenied,
-                .WSAEADDRNOTAVAIL => return error.AddressNotAvailable,
-                .WSAECONNRESET => return error.ConnectionResetByPeer,
-                .WSAEMSGSIZE => return error.MessageOversize,
-                .WSAENOBUFS => return error.SystemResources,
-                .WSAENOTSOCK => return error.FileDescriptorNotASocket,
-                .WSAEAFNOSUPPORT => return error.AddressFamilyUnsupported,
-                .WSAEDESTADDRREQ => unreachable, // A destination address is required.
-                .WSAEFAULT => unreachable, // The lpBuffers, lpTo, lpOverlapped, lpNumberOfBytesSent, or lpCompletionRoutine parameters are not part of the user address space, or the lpTo parameter is too small.
-                .WSAEHOSTUNREACH => return error.NetworkUnreachable,
-                // TODO: WSAEINPROGRESS, WSAEINTR
-                .WSAEINVAL => unreachable,
-                .WSAENETDOWN => return error.NetworkDown,
-                .WSAENETRESET => return error.ConnectionResetByPeer,
-                .WSAENETUNREACH => return error.NetworkUnreachable,
-                .WSAENOTCONN => return error.SocketUnconnected,
-                .WSAESHUTDOWN => unreachable, // The socket has been shut down; it is not possible to WSASendTo on a socket after shutdown has been invoked with how set to SD_SEND or SD_BOTH.
-                .WSAEWOULDBLOCK => return error.WouldBlock,
-                .WSANOTINITIALISED => unreachable, // A successful WSAStartup call must occur before using this function.
+                .EACCES => return error.AccessDenied,
+                .EADDRNOTAVAIL => return error.AddressUnavailable,
+                .ECONNRESET => return error.ConnectionResetByPeer,
+                .EMSGSIZE => return error.MessageOversize,
+                .ENOBUFS => return error.SystemResources,
+                .ENOTSOCK => return error.FileDescriptorNotASocket,
+                .EAFNOSUPPORT => return error.AddressFamilyUnsupported,
+                .EDESTADDRREQ => unreachable, // A destination address is required.
+                .EFAULT => unreachable, // The lpBuffers, lpTo, lpOverlapped, lpNumberOfBytesSent, or lpCompletionRoutine parameters are not part of the user address space, or the lpTo parameter is too small.
+                .EHOSTUNREACH => return error.NetworkUnreachable,
+                // TODO: EINPROGRESS, EINTR
+                .EINVAL => unreachable,
+                .ENETDOWN => return error.NetworkDown,
+                .ENETRESET => return error.ConnectionResetByPeer,
+                .ENETUNREACH => return error.NetworkUnreachable,
+                .ENOTCONN => return error.SocketUnconnected,
+                .ESHUTDOWN => unreachable, // The socket has been shut down; it is not possible to WSASendTo on a socket after shutdown has been invoked with how set to SD_SEND or SD_BOTH.
+                .EWOULDBLOCK => return error.WouldBlock,
+                .NOTINITIALISED => unreachable, // A successful WSAStartup call must occur before using this function.
                 else => |err| return windows.unexpectedWSAError(err),
             },
             else => |rc| return @intCast(rc),
@@ -5896,7 +5778,7 @@ pub fn send(
         error.FileNotFound => unreachable,
         error.NotDir => unreachable,
         error.NetworkUnreachable => unreachable,
-        error.AddressNotAvailable => unreachable,
+        error.AddressUnavailable => unreachable,
         error.SocketUnconnected => unreachable,
         error.UnreachableAddress => unreachable,
         else => |e| return e,
@@ -6007,9 +5889,9 @@ pub fn poll(fds: []pollfd, timeout: i32) PollError!usize {
     if (native_os == .windows) {
         switch (windows.poll(fds.ptr, @intCast(fds.len), timeout)) {
             windows.ws2_32.SOCKET_ERROR => switch (windows.ws2_32.WSAGetLastError()) {
-                .WSANOTINITIALISED => unreachable,
-                .WSAENETDOWN => return error.NetworkDown,
-                .WSAENOBUFS => return error.SystemResources,
+                .NOTINITIALISED => unreachable,
+                .ENETDOWN => return error.NetworkDown,
+                .ENOBUFS => return error.SystemResources,
                 // TODO: handle more errors
                 else => |err| return windows.unexpectedWSAError(err),
             },
@@ -6107,14 +5989,14 @@ pub fn recvfrom(
         if (native_os == .windows) {
             if (rc == windows.ws2_32.SOCKET_ERROR) {
                 switch (windows.ws2_32.WSAGetLastError()) {
-                    .WSANOTINITIALISED => unreachable,
-                    .WSAECONNRESET => return error.ConnectionResetByPeer,
-                    .WSAEINVAL => return error.SocketNotBound,
-                    .WSAEMSGSIZE => return error.MessageOversize,
-                    .WSAENETDOWN => return error.NetworkDown,
-                    .WSAENOTCONN => return error.SocketUnconnected,
-                    .WSAEWOULDBLOCK => return error.WouldBlock,
-                    .WSAETIMEDOUT => return error.Timeout,
+                    .NOTINITIALISED => unreachable,
+                    .ECONNRESET => return error.ConnectionResetByPeer,
+                    .EINVAL => return error.SocketNotBound,
+                    .EMSGSIZE => return error.MessageOversize,
+                    .ENETDOWN => return error.NetworkDown,
+                    .ENOTCONN => return error.SocketUnconnected,
+                    .EWOULDBLOCK => return error.WouldBlock,
+                    .ETIMEDOUT => return error.Timeout,
                     // TODO: handle more errors
                     else => |err| return windows.unexpectedWSAError(err),
                 }
@@ -6220,11 +6102,11 @@ pub fn setsockopt(fd: socket_t, level: i32, optname: u32, opt: []const u8) SetSo
         const rc = windows.ws2_32.setsockopt(fd, level, @intCast(optname), opt.ptr, @intCast(opt.len));
         if (rc == windows.ws2_32.SOCKET_ERROR) {
             switch (windows.ws2_32.WSAGetLastError()) {
-                .WSANOTINITIALISED => unreachable,
-                .WSAENETDOWN => return error.NetworkDown,
-                .WSAEFAULT => unreachable,
-                .WSAENOTSOCK => return error.FileDescriptorNotASocket,
-                .WSAEINVAL => return error.SocketNotBound,
+                .NOTINITIALISED => unreachable,
+                .ENETDOWN => return error.NetworkDown,
+                .EFAULT => unreachable,
+                .ENOTSOCK => return error.FileDescriptorNotASocket,
+                .EINVAL => return error.SocketNotBound,
                 else => |err| return windows.unexpectedWSAError(err),
             }
         }