Services are distinguished by the port number, which is in the TCP header, and a given service (HTTP, FTP, TIME) will have a process on the server listening on a given port number. (Specifically, the connection is in LISTEN state, see RFC 768 Figure 6 on p23). In the same way as the client process knows which host to contact (typically because some human asked for it or configured it), it knows what the server's port number will be because it will be what's called a "well-known port number". The operating system knows these part of its configuration.
For the major services (web, mail, telnet, ssh, etc) the allocation was done by convention: the "well known port numbers" were established by documenting what everybody was using in 1972: "We would like to catalog other sockets which are supposed to be well-known, so we would appreciate having a note or phone call ..." RFC 322. Remember at that time it wasn't clear which services were going to be important, or indeed that the internet would grow the way it did. By 1994 it had evolved into part of the "Assigned Numbers" list, last published as RFC 1700. Even that got out of hand, so was replaced with an online registry. Wikipedia has a decent summary. Nowadays, most things which once upon a time might have had their own socket number, such as whois, would today be done by XML/HTTP or similar.
Within a given system, the port numbers might be hard-coded or looked up with an operating system specific mechanism. For example, the Berkeley sockets software, which was the model for most internet implementations, provides a getservbyname()
library call, which normally looked things up a file /etc/services
; other operating systems have analogous mechanisms.