Chapter 4 ■ SoCket NameS aNd dNS
65
Primitive Name Service Routines
Before getaddrinfo() was all the rage, programmers doing socket-level programming got by with a simpler collection
of name service routines supported by the operating system. They should be avoided today since most of them are
hardwired to speak only IPv4.
You can find their documentation in the Standard Library page on the socket module. Here, I will show a few
quick examples to illustrate each call. Two calls return the hostname of the current machine.
socket.gethostname()
'asaph'
socket.getfqdn()
'asaph.rhodesmill.org'
And two more let you convert between IPv4 hostnames and IP addresses.
socket.gethostbyname('cern.ch')
'137.138.144.169'
socket.gethostbyaddr('137.138.144.169')
('webr8.cern.ch', [], ['137.138.144.169'])
Finally, three routines let you look up protocol numbers and ports using symbolic names known to your
operating system.
socket.getprotobyname('UDP')
17
socket.getservbyname('www')
80
socket.getservbyport(80)
'www'
If you want to try learning the primary IP address for the machine on which your Python program is running, you
can try passing its fully qualified hostname into a gethostbyname() call, like this:
socket.gethostbyname(socket.getfqdn())
'74.207.234.78'
However, since either call could fail and return an address error (see the section on error handling in Chapter 5),
your code should have a backup plan in case this pair of calls fails to return a useful IP address.
Using getsockaddr() in Your Own Code
To put everything together, I have assembled a quick example of how getaddrinfo() looks in actual code. Take a look
at Listing 4-1.
Listing 4-1. Using getaddrinfo() to Create and Connect a Socket
#!/usr/bin/env python3