Foundations of Python Network Programming

(WallPaper) #1
Chapter 2 ■ UDp

31

Do you see what happened? Programs running locally are allowed to send requests that originate from any of the
machine’s IP addresses that they want—even if they are just using that IP address to talk back to another service on
the same machine!
So, binding to an IP interface might limit which external hosts can talk to you. But it will certainly not limit
conversations with other clients on the same machine, so long as they know the IP address to which they should
connect.
What happens if you try to run two servers at the same time? Stop all of the scripts that are running and try
running two servers on the same box. You will connect one to the loopback.


$ python udp_remote.py server 127.0.0.1
Listening at ('127.0.0.1', 1060)


Now that that address is occupied, you cannot run a second server at that address, because then the operating
system would not know which process should get any given packet arriving at that address.


$ python udp_remote.py server 127.0.0.1
Traceback (most recent call last):
...
OSError: [Errno 98] Address already in use


But what might be more surprising is that you will not be able to run a server on the wildcard IP address either.

$ python udp_remote.py server
Traceback (most recent call last):
...
OSError: [Errno 98] Address already in use


This fails because the wildcard address includes 127.0.0.1, and therefore it conflicts with the address that the first
server process has already grabbed. But what if instead of trying to run the second server against all IP interfaces, you
just ran it against an external IP interface—one that the first copy of the server is not listening to? Let’s try.


$ python udp_remote.py server 192.168.5.130
Listening at ('192.168.5.130', 1060)


It worked! There are now two servers running on this machine with the same UDP port number, one of which is
bound to the inward-looking loopback interface and the other is looking outward for packets arriving on the network
to which my wireless card has connected. If you happen to be on a box with several remote interfaces, you can start up
even more servers, one on each remote interface.
Once you have these servers running, try to send them some packets with your UDP client. You will find that only
one server receives each request, and in each case it will be the server that holds the particular IP address to which
you have directed the UDP request packet.
The lesson of all of this is that an IP network stack never thinks of a UDP port as a lone entity that is either entirely
available or else in use, at any given moment. Instead, it thinks in terms of UDP “socket names” that are always a pair
linking an IP interface—even if it is the wildcard interface—with a UDP port number. It is these socket names that
must not conflict among the listening servers at any given moment, rather than the bare UDP ports that are in use.

Free download pdf