Skip to content

Commit

Permalink
fix
Browse files Browse the repository at this point in the history
  • Loading branch information
felipensp committed Sep 28, 2024
1 parent f30078a commit 598115d
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 12 deletions.
31 changes: 31 additions & 0 deletions vlib/net/address_test.v
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import net

fn test_empty_port() {
host, port := net.split_address('192.168.1.100')!
assert port == 0
assert host == '192.168.1.100'
}

fn test_with_port() {
host, port := net.split_address('192.168.1.100:1919')!
assert port == 1919
assert host == '192.168.1.100'
}

fn test_empty_port_ipv6() {
host, port := net.split_address('[::1]')!
assert port == 0
assert host == '::1'
}

fn test_with_port_ipv6() {
host, port := net.split_address('[::1]:1919')!
assert port == 1919
assert host == '::1'
}

fn test_without_port_ipv6() {
host, port := net.split_address('::1')!
assert port == 0
assert host == '::1'
}
35 changes: 23 additions & 12 deletions vlib/net/util.v
Original file line number Diff line number Diff line change
Expand Up @@ -15,17 +15,28 @@ 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()
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]
if _ := addr.index(']') {
// ipv6 brackets
address := addr.all_after('[').all_before_last(']')
port := addr.all_after_last(']:').int()
p := validate_port(port)!
return address, p
} else if _ := addr.index(':') {
// ipv6 ::1
if addr.all_before_last(':').trim(':') == '' {
return addr, 0
} else {
// ip:port
address := addr.all_before_last(':')
port := addr.all_after_last(':').int()
p := validate_port(port)!
return address, p
}
} else {
// addr only
port := 0
address := addr.all_before_last(':')
p := validate_port(port)!
return address, p
}

p := validate_port(port)!
return address, p
}

0 comments on commit 598115d

Please sign in to comment.