net: fix TcpConn.peer_ip/0 to only return the ip address, without the port number (#21831)

This commit is contained in:
Swastik Baranwal 2024-07-10 08:42:37 +05:30 committed by GitHub
parent ca07347430
commit 547c056bf4
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 16 additions and 1 deletions

View File

@ -297,7 +297,15 @@ pub fn (c &TcpConn) peer_addr() !Addr {
// peer_ip retrieves the ip address used by the peer, and returns it as a string
pub fn (c &TcpConn) peer_ip() !string {
return c.peer_addr()!.str()
address := c.peer_addr()!.str()
if address.contains(']:') {
// ipv6 addresses similar to this: '[::1]:46098'
ip := address.all_before(']:').all_after('[')
return ip
}
// ipv4 addresses similar to '127.0.0.1:7346'
ip := address.all_before(':')
return ip
}
pub fn (c &TcpConn) addr() !Addr {

View File

@ -64,6 +64,10 @@ fn test_socket() {
fn test_socket_write_and_read() {
mut server, mut client, mut socket := setup()
addr := socket.peer_addr()!
ip := socket.peer_ip()!
assert ip in ['::1', 'localhost', '127.0.0.1']
println('> ip: ${ip} | addr: ${addr}')
defer {
cleanup(mut server, mut client, mut socket)
}

View File

@ -35,6 +35,9 @@ fn echo(address string) ! {
println('local: ' + c.addr()!.str())
println(' peer: ' + c.peer_addr()!.str())
ip := c.peer_ip()!
println(' ip: ${ip}')
assert ip in ['::1', 'localhost', '127.0.0.1']
data := 'Hello from vlib/net!'
c.write_string(data)!