From 5813d2bf72bb3d55d3284be0e50cfe98a3e7dcb0 Mon Sep 17 00:00:00 2001 From: Delyan Angelov Date: Thu, 2 Jul 2020 22:27:36 +0300 Subject: [PATCH] net.socket: add s.peer_ip() --- vlib/net/init_nix.c.v | 1 + vlib/net/socket.v | 27 ++++++++++++++++++++++----- vlib/net/socket_test.v | 6 +++++- 3 files changed, 28 insertions(+), 6 deletions(-) diff --git a/vlib/net/init_nix.c.v b/vlib/net/init_nix.c.v index 271f81c68e..c31100f22f 100644 --- a/vlib/net/init_nix.c.v +++ b/vlib/net/init_nix.c.v @@ -3,6 +3,7 @@ module net #include #include #include +#include #include #include fn error_code() int { diff --git a/vlib/net/socket.v b/vlib/net/socket.v index 0b58a66a45..b95aa47591 100644 --- a/vlib/net/socket.v +++ b/vlib/net/socket.v @@ -70,6 +70,10 @@ fn C.ntohs() int fn C.getsockname() int +fn C.inet_ntop(af int, src voidptr, dst charptr, dst_size int) charptr + +fn C.getpeername(sockfd int, addr &C.sockaddr_in, addrsize &int) int + // create socket pub fn new_socket(family, typ, proto int) ?Socket { sockfd := C.socket(family, typ, proto) @@ -166,11 +170,9 @@ pub fn (s Socket) accept() ?Socket { $if debug { println('accept()') } - addr := C.sockaddr_storage{} - size := 128 // sizeof(sockaddr_storage) - tmp := voidptr(&addr) - skaddr := &C.sockaddr(tmp) - sockfd := C.accept(s.sockfd, skaddr, &size) + addr := C.sockaddr{} + size := sizeof(addr) + sockfd := C.accept(s.sockfd, &addr, &size) if sockfd < 0 { return error('net.accept: failed with $sockfd') } @@ -183,6 +185,21 @@ pub fn (s Socket) accept() ?Socket { return c } +pub fn (s Socket) peer_ip() ?string { + buf := [44]byte + peeraddr := C.sockaddr_in{} + speeraddr := sizeof(peeraddr) + ok := C.getpeername(s.sockfd, &C.sockaddr(&peeraddr), &speeraddr) + if ok == -1 { + return error('net.peer_ip: getpeername failed') + } + cstr := C.inet_ntop(C.AF_INET, &peeraddr.sin_addr, buf, sizeof(buf)) + if cstr == 0 { + return error('net.peer_ip: inet_ntop failed') + } + return cstring_to_vstring(cstr) +} + // connect to given addrress and port pub fn (s Socket) connect(address string, port int) ?int { mut hints := C.addrinfo{} diff --git a/vlib/net/socket_test.v b/vlib/net/socket_test.v index 20d6373228..6b8cf5bc55 100644 --- a/vlib/net/socket_test.v +++ b/vlib/net/socket_test.v @@ -3,8 +3,12 @@ import net fn setup() (net.Socket, net.Socket, net.Socket) { server := net.listen(0) or { panic(err) } server_port := server.get_port() - client := net.dial('127.0.0.1', server_port) or { panic(err) } + client := net.dial('127.0.0.1', server_port) or { panic(err) } socket := server.accept() or { panic(err) } + $if debug_peer_ip ? { + ip := socket.peer_ip() or { '$err' } + eprintln('socket peer_ip: $ip') + } return server, client, socket }