Chapter 2 ■ UDp
33
if not hasattr(IN, 'IP_MTU'):
raise RuntimeError('cannot perform MTU discovery on this combination'
' of operating system and Python distribution')
def send_big_datagram(host, port):
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.setsockopt(socket.IPPROTO_IP, IN.IP_MTU_DISCOVER, IN.IP_PMTUDISC_DO)
sock.connect((host, port))
try:
sock.send(b'#' * 65000)
except socket.error:
print('Alas, the datagram did not make it')
max_mtu = sock.getsockopt(socket.IPPROTO_IP, IN.IP_MTU)
print('Actual MTU: {}'.format(max_mtu))
else:
print('The big datagram was sent!')
if name == 'main':
parser = argparse.ArgumentParser(description='Send UDP packet to get MTU')
parser.add_argument('host', help='the host to which to target the packet')
parser.add_argument('-p', metavar='PORT', type=int, default=1060,
help='UDP port (default 1060)')
args = parser.parse_args()
send_big_datagram(args.host, args.p)
If I run this program against a server elsewhere on my home network, then I discover that my wireless network
allows physical packets that are no bigger than the 1,500 bytes typically supported by Ethernet-style networks.
$ python big_sender.py guinness
Alas, the datagram did not make it
Actual MTU: 1500
It is slightly more surprising that the loopback interface on my laptop, which presumably could support packets
as large as my RAM, also imposes an MTU.
$ python big_sender.py 127.0.0.1
Alas, the datagram did not make it
Actual MTU: 65535
But the ability to check the MTU is not available everywhere; check your operating system documentation
for details.
Socket Options
The POSIX socket interface supports all sorts of socket options that control specific behaviors of network sockets. The
IP_MTU_DISCOVER option that you saw in Listing 2-3 is just the tip of the iceberg. Options are accessed through the
Python socket methods getsockopt() and setsockopt(), using the options that your operating system’s documentation
lists for these two system calls. On Linux, try viewing the manual pages socket(7), udp(7), and—when you progress to the
next chapter—tcp(7).