net: add a .port()! method for net.Addr (#21412)

This commit is contained in:
vcker 2024-05-06 01:12:33 +08:00 committed by GitHub
parent 598de74185
commit a4cdc48542
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 27 additions and 0 deletions

View file

@ -60,6 +60,28 @@ pub fn (a Addr) family() AddrFamily {
return unsafe { AddrFamily(a.f) } return unsafe { AddrFamily(a.f) }
} }
// port returns the ip or ip6 port of the given address `a`
pub fn (a Addr) port() !u16 {
match unsafe { AddrFamily(a.f) } {
.ip {
unsafe {
return conv.ntoh16(a.addr.Ip.port)
}
}
.ip6 {
unsafe {
return conv.ntoh16(a.addr.Ip6.port)
}
}
.unix {
return error('unix addr has no port')
}
.unspec {
return error('unspec addr family when obtain port')
}
}
}
const max_ip_len = 24 const max_ip_len = 24
const max_ip6_len = 46 const max_ip6_len = 46

View file

@ -1,5 +1,10 @@
module net module net
fn test_ip_port() {
assert new_ip(1234, addr_ip_any).port()! == 1234
assert new_ip6(1234, addr_ip6_any).port()! == 1234
}
fn test_diagnostics() { fn test_diagnostics() {
dump(aoffset) dump(aoffset)
eprintln('--------') eprintln('--------')