Sockets, DNS and cancellation
Sockets, DNS and cancellation
DNS maps host names to addresses; it does not establish a connection or authorize access. TCP supplies an ordered byte stream, not application messages. UDP transports datagrams without TCP-style delivery or ordering guarantees. HttpClient adds HTTP semantics above transport, and TLS authenticates peers and protects traffic when configured correctly. Network code needs cancellation, finite buffers and explicit ownership at every stage. Only one example opens a socket, on loopback with an OS-assigned ephemeral port, and only when a learner runs the fixture in an approved environment.
Baseline: .NET 10 / C# 14 (SDK candidate inherited, not installed). Each example is an independent project with predicted output. Build and runtime verification are pending. Run only a reviewed fixture in an approved disposable environment.
Describe an endpoint without resolving a host
Use a literal loopback address and a hypothetical port. This does not open a socket.
using System;using System.Net;var address = IPAddress.Parse("127.0.0.1");var endpoint = new IPEndPoint(address, 8080);Console.WriteLine(IPAddress.IsLoopback(address));Console.WriteLine(endpoint.Port);An endpoint combines an address and port; it does not identify a URL path or guarantee a listening service. Host names may resolve to multiple IPv4/IPv6 addresses.
Expected observation (reasoned, not executed):
True8080Exchange a fixed frame over local TCP
The listener binds only to IPv4 loopback on a port selected by the OS. Both connections and all reads are bounded by a cancellation token.
using System;using System.Net;using System.Net.Sockets;using System.Text;using System.Threading;using var deadline = new CancellationTokenSource(TimeSpan.FromSeconds(10));var listener = new TcpListener(IPAddress.Loopback, 0);listener.Start();try{ int port = ((IPEndPoint)listener.LocalEndpoint).Port; using var client = new TcpClient(AddressFamily.InterNetwork); await client.ConnectAsync(IPAddress.Loopback, port, deadline.Token); using var peer = await listener.AcceptTcpClientAsync(deadline.Token); using NetworkStream sender = client.GetStream(); using NetworkStream receiver = peer.GetStream(); await sender.WriteAsync("ping"u8.ToArray(), deadline.Token); byte[] frame = new byte[4]; await receiver.ReadExactlyAsync(frame, deadline.Token); Console.WriteLine(Encoding.ASCII.GetString(frame));}finally { listener.Stop(); }ReadExactlyAsync handles partial reads until the four-byte frame is filled or an error occurs. A real protocol must define framing and limits. A local TCP test does not test TLS, DNS, HTTP or public connectivity.
Expected observation (reasoned, not executed):
pingReject a truncated stream frame offline
A MemoryStream simulates an early end of input. The consumer must not interpret a partially filled buffer as a full message.
using System;using System.IO;using System.Threading;using var stop = new CancellationTokenSource();using var input = new MemoryStream("ab"u8.ToArray());byte[] frame = new byte[4];try{ await input.ReadExactlyAsync(frame, stop.Token); Console.WriteLine("complete");}catch (EndOfStreamException) { Console.WriteLine("truncated"); }The stream has two bytes, not the four required by the chosen protocol. EndOfStreamException is different from cancellation and should not be treated as a valid empty message.
Expected observation (reasoned, not executed):
truncatedCommon mistakes and design limits
Use Dns.GetHostAddressesAsync(host, token) only for an authorized known hostname; do not assume one address or a fixed resolution order. Cancellation is cooperative and platform-dependent. A TCP read can return fewer bytes than requested or zero at orderly end of input; use explicit framing and reject oversized lengths before allocating. Never connect to arbitrary user-controlled endpoints, disable certificate verification, or assume a successful TCP handshake proves application authorization. For production networking, test IPv6, DNS changes, connection failures and TLS separately. The loopback fixture needs an approved environment supporting local sockets.
Apply the concept
A protocol declares fixed four-byte messages. A TCP receiver reads 1, then 2, then 1 byte; the next message ends after 2 bytes. Explain the two outcomes and where cancellation belongs.
Check your work: The first four bytes form one valid frame; the next two bytes are truncated and rejected. Pass the same bounded operation token to connect and each read, and close the connection on unrecoverable framing failure.
Further study
Continue with the next planned lesson. Consult the official documentation for API contracts: tcpclient, dns, socketconnect, accepttcp, readexactly. API and runtime verification remain incomplete.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Sockets, DNS and cancellation — knowledge check
Apply the lesson concepts to the following scenarios.
What does DNS resolution return?
A TCP read returns two of four requested bytes. What next?
What does a zero-byte TCP stream read with a nonempty buffer usually mean?
Why bind the lab listener to port zero?
What does the loopback example establish if it passes?