net: make listen/bind errors more informative

pull/13100/head
Delyan Angelov 2022-01-08 17:02:03 +02:00
parent 9cbfa882e6
commit b778c1d097
No known key found for this signature in database
GPG Key ID: 66886C0F12D595ED
2 changed files with 18 additions and 9 deletions

View File

@ -20,6 +20,10 @@ pub const (
err_timed_out_code = errors_base + 9 err_timed_out_code = errors_base + 9
) )
pub fn socket_error_message(potential_code int, s string) ?int {
return socket_error(potential_code) or { return error('$err.msg; $s') }
}
pub fn socket_error(potential_code int) ?int { pub fn socket_error(potential_code int) ?int {
$if windows { $if windows {
if potential_code < 0 { if potential_code < 0 {

View File

@ -20,11 +20,15 @@ mut:
} }
pub fn dial_tcp(address string) ?&TcpConn { pub fn dial_tcp(address string) ?&TcpConn {
addrs := resolve_addrs_fuzzy(address, .tcp) ? addrs := resolve_addrs_fuzzy(address, .tcp) or {
return error('$err.msg; could not resolve address $address in dial_tcp')
}
// Very simple dialer // Very simple dialer
for addr in addrs { for addr in addrs {
mut s := new_tcp_socket(addr.family()) ? mut s := new_tcp_socket(addr.family()) or {
return error('$err.msg; could not create new tcp socket in dial_tcp')
}
s.connect(addr) or { s.connect(addr) or {
// Connection failed // Connection failed
s.close() or { continue } s.close() or { continue }
@ -38,7 +42,7 @@ pub fn dial_tcp(address string) ?&TcpConn {
} }
} }
// failed // failed
return error('dial_tcp failed') return error('dial_tcp failed for address $address')
} }
pub fn (mut c TcpConn) close() ? { pub fn (mut c TcpConn) close() ? {
@ -185,7 +189,7 @@ pub fn (c &TcpConn) peer_addr() ?Addr {
} }
} }
mut size := sizeof(Addr) mut size := sizeof(Addr)
socket_error(C.getpeername(c.sock.handle, voidptr(&addr), &size)) ? socket_error_message(C.getpeername(c.sock.handle, voidptr(&addr), &size), 'peer_addr failed') ?
return addr return addr
} }
@ -211,18 +215,19 @@ mut:
} }
pub fn listen_tcp(family AddrFamily, saddr string) ?&TcpListener { pub fn listen_tcp(family AddrFamily, saddr string) ?&TcpListener {
s := new_tcp_socket(family) ? s := new_tcp_socket(family) or { return error('$err.msg; could not create new socket') }
addrs := resolve_addrs(saddr, family, .tcp) ? addrs := resolve_addrs(saddr, family, .tcp) or {
return error('$err.msg; could not resolve address $saddr')
}
// TODO(logic to pick here) // TODO(logic to pick here)
addr := addrs[0] addr := addrs[0]
// cast to the correct type // cast to the correct type
alen := addr.len() alen := addr.len()
bindres := C.bind(s.handle, voidptr(&addr), alen) socket_error_message(C.bind(s.handle, voidptr(&addr), alen), 'binding to $saddr failed') ?
socket_error(bindres) ? socket_error_message(C.listen(s.handle, 128), 'listening on $saddr failed') ?
socket_error(C.listen(s.handle, 128)) ?
return &TcpListener{ return &TcpListener{
sock: s sock: s
accept_deadline: no_deadline accept_deadline: no_deadline