net: properly convert IP address C strings to V strings (#12648)

pull/12664/head
Miccah 2021-12-02 03:18:14 -06:00 committed by GitHub
parent 9cf7af0c75
commit 799d7b843c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 20 additions and 6 deletions

View File

@ -66,30 +66,30 @@ const (
) )
fn (a Ip) str() string { fn (a Ip) str() string {
buf := []byte{len: net.max_ip_len, init: 0} buf := [net.max_ip_len]char{}
res := &char(C.inet_ntop(.ip, &a.addr, buf.data, buf.len)) res := &char(C.inet_ntop(.ip, &a.addr, &buf[0], buf.len))
if res == 0 { if res == 0 {
return '<Unknown>' return '<Unknown>'
} }
saddr := buf.bytestr() saddr := unsafe { cstring_to_vstring(&buf[0]) }
port := C.ntohs(a.port) port := C.ntohs(a.port)
return '$saddr:$port' return '$saddr:$port'
} }
fn (a Ip6) str() string { fn (a Ip6) str() string {
buf := []byte{len: net.max_ip6_len, init: 0} buf := [net.max_ip_len]char{}
res := &char(C.inet_ntop(.ip6, &a.addr, buf.data, buf.len)) res := &char(C.inet_ntop(.ip6, &a.addr, &buf[0], buf.len))
if res == 0 { if res == 0 {
return '<Unknown>' return '<Unknown>'
} }
saddr := buf.bytestr() saddr := unsafe { cstring_to_vstring(&buf[0]) }
port := C.ntohs(a.port) port := C.ntohs(a.port)
return '[$saddr]:$port' return '[$saddr]:$port'

View File

@ -96,3 +96,17 @@ fn test_sizes_ipv4() {
fn test_sizes_unix() { fn test_sizes_unix() {
assert sizeof(C.sockaddr_un) == sizeof(Unix) + aoffset assert sizeof(C.sockaddr_un) == sizeof(Unix) + aoffset
} }
fn test_ip_str() {
ip := new_ip(1337, addr_ip_any).str()
expected := '0.0.0.0:1337'
assert ip.len == expected.len
assert ip == expected
}
fn test_ip6_str() {
ip := new_ip6(1337, addr_ip6_any).str()
expected := '[::]:1337'
assert ip.len == expected.len
assert ip == expected
}