Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

net: allow ipv6 address with brackets #22316

Merged
merged 3 commits into from
Sep 26, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
}
Loading