1
0
mirror of https://github.com/vlang/v.git synced 2023-08-10 21:13:21 +03:00

net.socket: add s.peer_ip()

This commit is contained in:
Delyan Angelov 2020-07-02 22:27:36 +03:00
parent b89cbf3224
commit 5813d2bf72
3 changed files with 28 additions and 6 deletions

View File

@ -3,6 +3,7 @@ module net
#include <sys/socket.h>
#include <unistd.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <errno.h>
fn error_code() int {

View File

@ -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{}

View File

@ -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
}