Tutorial 3: A Simple TCP Client
Adapted from Spectranet: Tutorial 3.
A TCP client is close to a TCP server in structure: it opens a socket, transfers data, and closes the socket. The main differences are that it usually resolves a remote host name and calls connect instead of bind, listen, and accept.
Client flow
A TCP client normally:
- resolves the remote host with
gethostbyname - opens a socket with
socket - connects to the remote address and port with
connect - sends and receives data with
sendandrecv - closes the socket
The tutorial example connects to a web server on port 80 and sends a simple HTTP request:
GET / HTTP/1.0
Host lookup
gethostbyname accepts a null-terminated string containing either a hostname or a dotted IPv4 address. It writes a four-byte big-endian IP address to the caller's buffer.
In assembly:
ld hl, remote_host
ld de, ip_buffer
ld ix, GETHOSTBYNAME
call IXCALL
jr c, .error
C code uses the BSD-style hostent return value:
struct hostent *he;
he = gethostbyname("spectrum.alioth.net");
if (!he) {
printk("Could not look up host!\n");
return;
}
It is best to resolve names before opening multiple sockets because DNS lookup itself uses socket resources.
Connecting and transferring data
After opening a SOCK_STREAM socket, connect associates it with the remote IP address and port. Once connected, send and recv work in the same style as in the server example.
Common connection failures include refused connections, timeouts, and unreachable hosts.