diff --git a/vlib/net/socket.v b/vlib/net/socket.v index 246ce171bf..f2a02f7997 100644 --- a/vlib/net/socket.v +++ b/vlib/net/socket.v @@ -45,9 +45,10 @@ mut: ai_socktype int ai_flags int ai_protocol int - ai_addrlen int - ai_next voidptr + ai_addrlen int ai_addr voidptr + ai_canonname voidptr + ai_next voidptr } struct C.sockaddr_storage {} @@ -175,6 +176,10 @@ pub fn (s Socket) connect(address string, port int) ?int { hints.ai_family = C.AF_UNSPEC hints.ai_socktype = C.SOCK_STREAM hints.ai_flags = C.AI_PASSIVE + hints.ai_addrlen = 0 + hints.ai_canonname = C.NULL + hints.ai_addr = C.NULL + info := &C.addrinfo{!} sport := '$port' @@ -263,7 +268,7 @@ const ( ) pub fn (s Socket) write(str string) { line := '$str\r\n' - C.write(s.sockfd, line.str, line.len) + C.send(s.sockfd, line.str, line.len, 0) } pub fn (s Socket) read_line() string { @@ -306,4 +311,11 @@ pub fn (s Socket) read_line() string { return res } +pub fn (s Socket) get_port() int { + mut addr := C.sockaddr_in {} + size := 16 // sizeof(sockaddr_in) + sockname_res := C.getsockname(s.sockfd, &addr, &size) + return int(C.ntohs(addr.sin_port)) +} + diff --git a/vlib/net/socket_test.v b/vlib/net/socket_test.v index 47a4375807..4c23c588a7 100644 --- a/vlib/net/socket_test.v +++ b/vlib/net/socket_test.v @@ -1,30 +1,29 @@ import net fn test_socket() { -// server := net.listen(8080) or { -// println(err) -// return -// } -// println(server) -// client := net.dial('127.0.0.1', 8080) or { -// println(err) -// return -// } -// println(client) -// socket := server.accept() or { -// println(err) -// return -// } -// println(socket) -// -// message := 'Hello World' -// socket.send(message.str, message.len) -// println('Sent: ' + message) -// -// bytes := client.recv(1024) -// println('Received: ' + tos(bytes, message.len)) -// -// server.close() -// client.close() -// socket.close() + mut server := net.listen(0) or { + println(err) + return + } + server_port := server.get_port() + mut client := net.dial('127.0.0.1', server_port) or { + println(err) + return + } + mut socket := server.accept() or { + println(err) + return + } + + message := 'Hello World' + socket.send(message.str, message.len) + + bytes := client.recv(1024) + received := tos(bytes, message.len) + + assert message == received + + server.close() + client.close() + socket.close() }