Networking
The std/net module talks to other machines. It has three parts: IP
addresses and host lookup, TCP and UDP sockets, and URLs. Like std/fs, every
operation that can fail returns a Result, so a refused connection or a
malformed address is a value you look at, not a crash.
#import "std/net"
'' An address from text, printed back in its standard form.
var a = net.ParseIp( "2001:DB8:0:0::1" )
print a.Value( ).ToString( )
'' Every failure is a value with a reason.
var bad = net.ParseIp( "300.1.2.3" )
print bad.IsOk( ), bad.Failure( ).Message( )
'' A URL taken apart.
var u = net.ParseUrl( "https://example.com/a%20b?x=1" )
print u.Value( ).Host, u.Value( ).Path, u.Value( ).RawQuery
Output
2001:db8::1
false ParseIp '300.1.2.3': invalid address
example.com /a b x=1
ParseIp reads an address and ToString( ) writes it back in its standard
form, which for IPv6 is lower case with the longest run of zeros written ::.
300.1.2.3 is not an address, and the failure's Message( ) says which call
refused what. ParseUrl takes a URL apart into fields; the path comes back
decoded, %20 as a space.
Every socket call waits until it is done or until its timeout runs out. The examples in this section connect only to this machine, so they run anywhere, with or without a network.
The pages in this section:
- Addresses: IPv4 and IPv6, ports, and looking up a name.
- TCP: a connection, which reads and writes like a file.
- UDP: single messages, sent and received whole.
- URLs: taking URLs apart, resolving links, query strings.
- HTTP: fetching a web page, with
httporhttps.
Activities
- Parse
"::1"and printIsLoopback( ). - Print
u.Value( ).Query( ).Get( "x" ).ValueOr( "" )for the URL above.