09.11.2016 Views

Foundations of Python Network Programming 978-1-4302-3004-5

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

CHAPTER 4 ■ SOCKET NAMES AND DNS<br />

If you are curious about how this works behind the scenes, read up on the relevant international<br />

standards starting with RFC 3492, and note that <strong>Python</strong> now includes an idna codec that can translate to<br />

and from internationalized domain names:<br />

>>> u'π.'.encode('idna')<br />

'xn--hxajbheg2az3al.xn--jxalpdlp'<br />

It is this resulting plain-ASCII string that is actually sent to the domain name service when you enter<br />

the Greek sample domain name just shown.<br />

Primitive Name Service Routines<br />

Before getaddrinfo() was all the rage, programmers doing socket-level programming got by with a<br />

simpler collection <strong>of</strong> name service routines supported by the operating system. They should be avoided<br />

today since most <strong>of</strong> them are hardwired to speak only IPv4.<br />

You can find their documentation in the Standard Library page on the socket module. Here, the<br />

most efficient thing to do will be to play show-and-tell and use quick examples to illustrate each call.<br />

Two calls let you learn about the hostname <strong>of</strong> the current machine:<br />

>>> socket.gethostname()<br />

'asaph'<br />

>>> socket.getfqdn()<br />

'asaph.rhodesmill.org'<br />

And two more let you convert between IPv4 hostnames and IP addresses:<br />

>>> socket.gethostbyname('cern.ch')<br />

'137.138.144.169'<br />

>>> socket.gethostbyaddr('137.138.144.169')<br />

('webr8.cern.ch', [], ['137.138.144.169'])<br />

Finally, three routines let you look up protocol numbers and ports using symbolic names known to<br />

your operating system:<br />

>>> socket.getprotobyname('UDP')<br />

17<br />

>>> socket.getservbyname('www')<br />

80<br />

>>> socket.getservbyport(80)<br />

'www'<br />

If you want to try learning the primary IP address for the machine on which your <strong>Python</strong> program is<br />

running, you can try passing its fully qualified hostname into a gethostbyname() call, like this:<br />

>>> socket.gethostbyname(socket.getfqdn())<br />

'74.207.234.78'<br />

But since either call could fail and return an address error (see the section on error handling in<br />

Chapter 5), your code should have a backup plan in case this pair <strong>of</strong> calls fails to return a useful IP<br />

address.<br />

59

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!