From 5dfd5fa3e7aba322410ee94f3279aa35d83778f5 Mon Sep 17 00:00:00 2001 From: Justice Suh Date: Sat, 13 Jul 2019 17:29:00 -0400 Subject: [PATCH] net: add windows socket support --- vlib/net/socket.v | 59 +++++++++++++++++++++++++++++++++++-------- vlib/net/socket_mac.v | 5 ++++ vlib/net/socket_win.v | 5 ++++ 3 files changed, 58 insertions(+), 11 deletions(-) create mode 100644 vlib/net/socket_mac.v create mode 100644 vlib/net/socket_win.v diff --git a/vlib/net/socket.v b/vlib/net/socket.v index ffd9a5aa1b..0f148d89e8 100644 --- a/vlib/net/socket.v +++ b/vlib/net/socket.v @@ -1,9 +1,5 @@ module net -#include -#include -#include - struct Socket { pub: sockfd int @@ -25,8 +21,21 @@ import const ( SHUT_RD SHUT_WR SHUT_RDWR + SD_BOTH ) +// used for WinSock init +struct C.WSAData { +mut: + wVersion u16 + wHighVersion u16 + szDescription [257]byte + szSystemStatus [129]byte + iMaxSockets u16 + iMaxUdpDg u16 + lpVendorInfo byteptr +} + struct C.in_addr { mut: s_addr int @@ -54,6 +63,12 @@ struct C.sockaddr_storage {} // create socket pub fn socket(family int, _type int, proto int) Socket { + $if windows { + mut wsadata := C.WSAData{} + res := C.WSAStartup(0x202, &wsadata) + // TODO: throw error if WSAStartup fails + } + sockfd := C.socket(family, _type, proto) s := Socket { sockfd: sockfd @@ -185,14 +200,36 @@ pub fn (s Socket) recv(bufsize int) byteptr { // shutdown and close socket pub fn (s Socket) close() int { - shutdown_res := C.shutdown(s.sockfd, SHUT_RDWR) - if shutdown_res < 0 { - println('socket: shutdown failed') + // WinSock + $if windows { + C.WSACleanup() } - res := C.close(s.sockfd) - if res < 0 { - println('socket: close failed') + + $if windows { + shutdown_res := C.shutdown(s.sockfd, SD_BOTH) + if shutdown_res < 0 { + println('socket: shutdown failed') + } } + $else { + shutdown_res := C.shutdown(s.sockfd, SHUT_RDWR) + if shutdown_res < 0 { + println('socket: shutdown failed') + } + } + + $if windows { + res := C.closesocket(s.sockfd) + if res < 0 { + println('socket: close failed') + } + } + $else { + res := C.close(s.sockfd) + if res < 0 { + println('socket: close failed') + } + } + return 0 } - diff --git a/vlib/net/socket_mac.v b/vlib/net/socket_mac.v new file mode 100644 index 0000000000..0ee48b4f5c --- /dev/null +++ b/vlib/net/socket_mac.v @@ -0,0 +1,5 @@ +module net + +#include +#include +#include diff --git a/vlib/net/socket_win.v b/vlib/net/socket_win.v new file mode 100644 index 0000000000..b50da976fd --- /dev/null +++ b/vlib/net/socket_win.v @@ -0,0 +1,5 @@ +module net + +#flag -lws2_32 +#include +#include