Learning Python Network Programming

(Sean Pound) #1
Chapter 1

Layer 4 – TCP and UDP


Layer 4 is the first layer that we may want to work with in Python. This layer
can employ one of two protocols: the Transmission Control Protocol (TCP) and
the User Datagram Protocol (UDP). Both of these provide the common service of
end-to-end transportation of data between applications on different network devices.


Network ports

Although IP facilitates the transport of data from one network device to another,
it doesn't provide us with a way of letting the destination device know what it
should do with the data once it receives it. One possible solution to this would
be to program every process running on the destination device to check all of the
incoming data to see if they are interested in it, but this would quickly lead to
obvious performance and security problems.


TCP and UDP provide the answer by introducing the concept of ports.
A port is an endpoint, which is attached to one of the IP addresses assigned to
the network device. Ports are claimed by a process running on the device, and
the process is then said to be listening on that port. Ports are represented by a
16-bit number, so that each IP address on a device has 65,535 possible ports that the
processes can claim (port number 0 is reserved). Ports can only be claimed by one
process at a time, even though a process can claim more than one port at a time.


When a message is sent over the network through TCP or UDP, the sending
application sets the destination port number in the header of the TCP or UDP
packet. When the message arrives at the destination, the TCP or UDP protocol
implementation running on the receiving device reads the port number and then
delivers the message payload to the process that is listening on that port.


Port numbers need to be known before the messages are sent. The main
mechanism for this is convention. In addition to managing the IP address space,
it is also the responsibility of IANA to manage the assignment of port numbers to
network services.


A service is a class of application, for example a web server, or a DNS server, which
is usually tied to an application protocol. Ports are assigned to services rather than
specific applications, because it gives service providers the flexibility to choose what
kind of software they want to use to provide a service, without having to worry
about the users who would need to look up and connect to a new port number
simply because the server has started using Apache instead of IIS, for example.

Free download pdf