[Python编程(第4版)].(Programming.Python.4th.Edition).Mark.Lutz.文字版

(yzsuai) #1

run on top of sockets. In short, the standard Internet protocols define a structured way
to talk over sockets. They generally standardize both message formats and socket port
numbers:



  • Message formats provide structure for the bytes exchanged over sockets during
    conversations.

  • Port numbers are reserved numeric identifiers for the underlying sockets over which
    messages are exchanged.


Raw sockets are still commonly used in many systems, but it is perhaps more common
(and generally easier) to communicate with one of the standard higher-level Internet
protocols. As we’ll see, Python provides support for standard protocols, which auto-
mates most of the socket and message formatting details.


Port number rules


Technically speaking, socket port numbers can be any 16-bit integer value between 0
and 65,535. However, to make it easier for programs to locate the standard protocols,
port numbers in the range of 0 to 1023 are reserved and preassigned to the standard
higher-level protocols. Table 12-1 lists the ports reserved for many of the standard
protocols; each gets one or more preassigned numbers from the reserved range.


Table 12-1. Port numbers reserved for common protocols


Protocol Common function Port number Python module
HTTP Web pages 80 http.client, http.server
NNTP Usenet news 119 nntplib
FTP data default File transfers 20 ftplib
FTP control File transfers 21 ftplib
SMTP Sending email 25 smtplib
POP3 Fetching email 110 poplib
IMAP4 Fetching email 143 imaplib
Finger Informational 79 n/a
SSH Command lines 22 n/a: third party
Telnet Command lines 23 telnetlib

Clients and servers


To socket programmers, the standard protocols mean that port numbers 0 to 1023 are
off-limits to scripts, unless they really mean to use one of the higher-level protocols.
This is both by standard and by common sense. A Telnet program, for instance, can
start a dialog with any Telnet-capable machine by connecting to its port, 23; without
preassigned port numbers, each server might install Telnet on a different port. Similarly,
websites listen for page requests from browsers on port 80 by standard; if they did not,


Plumbing the Internet | 783
Free download pdf