Foundations of Python Network Programming

(WallPaper) #1

Chapter 2 ■ UDp


30


Binding to Interfaces


So far, you have seen two possibilities for the IP address used in the bind() call that the server makes. You can use
'127.0.0.1' to indicate that you want packets from other programs running only on the same machine, or you can
use an empty string '' as a wildcard to indicate that you are willing to receive packets arriving at the server via any of
its network interfaces.
There is a third choice. You can provide the IP address of one of the machine’s external IP interfaces, such as its
Ethernet connection or wireless card, and the server will listen only for packets destined for those IPs. You might have
noticed that Listing 2-2 actually allows you to provide a server string for the bind() call, which will now let you do a
few experiments.
What if you bind solely to an external interface? Run the server like this, using whatever your operating system
tells you is the external IP address of your system:


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


Connecting to this IP address from another machine should still work just fine.

$ python udp_remote.py client guinness
Client socket name is ('192.168.5.10', 35084)
Waiting up to 0.1 seconds for a reply
The server says 'Your data was 23 bytes'


But if you try connecting to the service through the loopback interface by running the client script on the same
machine, the packets will never be delivered.


$ python udp_remote.py client 127.0.0.1
Client socket name is ('127.0.0.1', 60251)
Waiting up to 0.1 seconds for a reply
Traceback (most recent call last):
...
socket.error: [Errno 111] Connection refused


Actually, on my operating system at least, the result is even better than the packets never being delivered.
Because the operating system can see whether one of its own ports is opened without sending a packet across the
network, it immediately replies that a connection to that port is impossible! But beware that this ability for UDP to
return “Connection refused” is a superpower of the loopback that you will never see on the real network. There the
packet must simply be sent with no indication of whether there is a destination port to receive it.
Try running the client again on the same machine, but this time use the external IP address of the box.


$ python udp_remote.py client 192.168.5.130
Client socket name is ('192.168.5.130', 34919)
Waiting up to 0.1 seconds for a reply
The server says 'Your data was 23 bytes'

Free download pdf