From 799d7b843c06c923afb9cf6eec3c7a45b3486948 Mon Sep 17 00:00:00 2001 From: Miccah Date: Thu, 2 Dec 2021 03:18:14 -0600 Subject: [PATCH] net: properly convert IP address C strings to V strings (#12648) --- vlib/net/address.v | 12 ++++++------ vlib/net/address_test.v | 14 ++++++++++++++ 2 files changed, 20 insertions(+), 6 deletions(-) diff --git a/vlib/net/address.v b/vlib/net/address.v index cb41eed8a3..bb204e152e 100644 --- a/vlib/net/address.v +++ b/vlib/net/address.v @@ -66,30 +66,30 @@ const ( ) 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 { return '' } - saddr := buf.bytestr() + saddr := unsafe { cstring_to_vstring(&buf[0]) } port := C.ntohs(a.port) return '$saddr:$port' } 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 { return '' } - saddr := buf.bytestr() + saddr := unsafe { cstring_to_vstring(&buf[0]) } port := C.ntohs(a.port) return '[$saddr]:$port' diff --git a/vlib/net/address_test.v b/vlib/net/address_test.v index fbec9fe370..167c43a5d0 100644 --- a/vlib/net/address_test.v +++ b/vlib/net/address_test.v @@ -96,3 +96,17 @@ fn test_sizes_ipv4() { fn test_sizes_unix() { 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 +}