Skip to content

Commit

Permalink
net: allow ipv6 address with brackets (fix #22313) (#22316)
Browse files Browse the repository at this point in the history
  • Loading branch information
felipensp committed Sep 26, 2024
1 parent 956f74a commit 9bc975e
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 6 deletions.
18 changes: 12 additions & 6 deletions vlib/net/util.v
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
module net

const socket_max_port = u16(0xFFFF)

// validate_port checks whether a port is valid
// and returns the port or an error
// validate_port checks whether a port is valid and returns the port or an error.
// The valid ports numbers are between 0 and 0xFFFF.
// For TCP, port number 0 is reserved and cannot be used, while for UDP, the source port
// is optional and a value of zero means no port.
// See also https://en.wikipedia.org/wiki/Port_%28computer_networking%29 .
pub fn validate_port(port int) !u16 {
if port <= socket_max_port {
if port >= 0 && port <= 0xFFFF {
return u16(port)
} else {
return err_port_out_of_range
Expand All @@ -15,11 +16,16 @@ pub fn validate_port(port int) !u16 {
// split_address splits an address into its host name and its port
pub fn split_address(addr string) !(string, u16) {
port := addr.all_after_last(':').int()
address := addr.all_before_last(':')
mut address := addr.all_before_last(':')

// TODO(emily): Maybe do some more checking here
// to validate ipv6 address sanity?

// RFC4038 - allow [::1]:port
if address.len > 0 && address[0] == `[` && address[address.len - 1] == `]` {
address = address[1..address.len - 1]
}

p := validate_port(port)!
return address, p
}
25 changes: 25 additions & 0 deletions vlib/net/utils_test.v
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import net

fn test_validate() {
assert net.validate_port(0)! == 0
assert net.validate_port(1)! == 1
assert net.validate_port(0xFFFF)! == 0xFFFF
if _ := net.validate_port(0xFFFF + 1) {
assert false
} else {
assert true
}
if x := net.validate_port(-2) {
dump(x)
assert false
} else {
assert true
}
}

fn test_resolve() {
x := net.resolve_addrs_fuzzy('[::1]:10093', .udp)!
assert x.len > 0
assert x[0].str() == '[::1]:10093'
assert x[0].port()! == 10093
}

0 comments on commit 9bc975e

Please sign in to comment.