Keyboard shortcuts

Press ← or β†’ to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Addresses

An IpAddress is an IPv4 or IPv6 address held as a value: copy it, compare it with Equals, print it with ToString( ). A SocketAddress is an address and a port β€” what a connection is made to.

#import "std/net"

sub Show( byref text as ustring )
    var r = net.ParseIp( text )
    if r.IsOk( ) = false then
        print text; ": refused"
        return
    end if
    var a = r.Value( )
    print text; " -> "; a.ToString( ); _
        iif( a.IsLoopback( ), " loopback", "" ); iif( a.IsPrivate( ), " private", "" ); _
        iif( a.IsMulticast( ), " multicast", "" ); iif( a.IsGlobalUnicast( ), " global", "" )
end sub

Show( "127.0.0.1" )
Show( "10.20.30.40" )
Show( "8.8.8.8" )
Show( "FF02:0:0:0:0:0:0:1" )
Show( "::ffff:192.168.0.1" )
Show( "192.168.000.001" )

'' A port makes a SocketAddress; IPv6 is written in brackets.
var sa = net.ParseSocketAddress( "[2001:db8::7]:443" ).Value( )
print sa.Ip.ToString( ), sa.Port

'' Building one, and comparing.
dim as net.SocketAddress local_ = net.SocketAddress( net.Loopback( ), 8080 )
print local_.ToString( ), local_.Equals( net.ParseSocketAddress( "127.0.0.1:8080" ).Value( ) )

'' A name is looked up; an address written as text comes back as itself.
var r = net.Resolve( "127.0.0.1", 80 )
print r.Value( ).Count( ), r.Value( )[ 0 ].ToString( )

Output

127.0.0.1 -> 127.0.0.1 loopback
10.20.30.40 -> 10.20.30.40 private global
8.8.8.8 -> 8.8.8.8 global
FF02:0:0:0:0:0:0:1 -> ff02::1 multicast
::ffff:192.168.0.1 -> ::ffff:192.168.0.1 private global
192.168.000.001: refused
2001:db8::7   443
127.0.0.1:8080              true
 1            127.0.0.1:80

Parsing is strict. 192.168.000.001 is refused: some programs read a leading zero as octal, others as decimal, and an address that two programs read differently is how a filter gets bypassed. IPv6 is accepted in any of its spellings and printed in one.

The Is… questions sort addresses into kinds: IsLoopback (this machine), IsPrivate (10/8, 172.16/12, 192.168/16, fc00::/7), IsLinkLocal, IsMulticast, IsUnspecified and IsGlobalUnicast. An IPv4 address written as IPv6 (::ffff:192.168.0.1) is answered as the IPv4 address it holds; Unmap( ) turns it back.

ParseSocketAddress needs the port, and brackets around an IPv6 address, because its colons would otherwise run into the port's. Loopback( ) and AnyAddress( ) are the two addresses a program names most: this machine, and every interface of it.

Resolve( host, port ) asks the system for a name's addresses and returns all of them, each with the port. An address written as text is returned as it is, without asking anyone.

Activities

  1. Add Show( "fe80::1%eth0" ) and print Zone( ) for it.
  2. Resolve "localhost" and print every address it has on your machine.