Skip to content

Commit

Permalink
net.ssl: implement SSLConn.peer_addr() (#19333)
Browse files Browse the repository at this point in the history
  • Loading branch information
trufae committed Sep 13, 2023
1 parent f8ba4ba commit 0244ae6
Show file tree
Hide file tree
Showing 4 changed files with 27 additions and 12 deletions.
16 changes: 13 additions & 3 deletions vlib/net/address.v
Expand Up @@ -294,14 +294,24 @@ pub fn (a Addr) str() string {

// addr_from_socket_handle returns an address, based on the given integer socket `handle`
pub fn addr_from_socket_handle(handle int) Addr {
addr := Addr{
mut addr := Addr{
addr: AddrData{
Ip6: Ip6{}
}
}
size := sizeof(addr)

mut size := sizeof(addr)
C.getsockname(handle, voidptr(&addr), &size)
return addr
}

// peer_addr_from_socket_handle retrieves the ip address and port number, given a socket handle
pub fn peer_addr_from_socket_handle(handle int) !Addr {
mut addr := Addr{
addr: AddrData{
Ip6: Ip6{}
}
}
mut size := sizeof(Addr)
socket_error_message(C.getpeername(handle, voidptr(&addr), &size), 'peer_addr_from_socket_handle failed')!
return addr
}
5 changes: 5 additions & 0 deletions vlib/net/mbedtls/ssl_connection.v
Expand Up @@ -405,6 +405,11 @@ pub fn (mut s SSLConn) dial(hostname string, port int) ! {
s.opened = true
}

// peer_addr retrieves the ip address and port number used by the peer
pub fn (s &SSLConn) peer_addr() !net.Addr {
return net.peer_addr_from_socket_handle(s.handle)
}

// socket_read_into_ptr reads `len` bytes into `buf`
pub fn (mut s SSLConn) socket_read_into_ptr(buf_ptr &u8, len int) !int {
mut res := 0
Expand Down
5 changes: 5 additions & 0 deletions vlib/net/openssl/ssl_connection.v
Expand Up @@ -280,6 +280,11 @@ fn (mut s SSLConn) complete_connect() ! {
}
}

// peer_addr retrieves the ip address and port number used by the peer
pub fn (s &SSLConn) peer_addr() !net.Addr {
return net.peer_addr_from_socket_handle(s.handle)
}

pub fn (mut s SSLConn) socket_read_into_ptr(buf_ptr &u8, len int) !int {
mut res := 0
$if trace_ssl ? {
Expand Down
13 changes: 4 additions & 9 deletions vlib/net/tcp.v
Expand Up @@ -4,7 +4,7 @@ import time
import io
import strings

const (
pub const (
tcp_default_read_timeout = 30 * time.second
tcp_default_write_timeout = 30 * time.second
)
Expand Down Expand Up @@ -252,17 +252,12 @@ pub fn (mut c TcpConn) set_sock() ! {
}
}

// peer_addr retrieves the ip address and port number used by the peer
pub fn (c &TcpConn) peer_addr() !Addr {
mut addr := Addr{
addr: AddrData{
Ip6: Ip6{}
}
}
mut size := sizeof(Addr)
socket_error_message(C.getpeername(c.sock.handle, voidptr(&addr), &size), 'peer_addr failed')!
return addr
return peer_addr_from_socket_handle(c.sock.handle)
}

// peer_ip retrieves the ip address used by the peer, and returns it as a string
pub fn (c &TcpConn) peer_ip() !string {
return c.peer_addr()!.str()
}
Expand Down

0 comments on commit 0244ae6

Please sign in to comment.