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 />

Using getsockaddr() in Your Own Code<br />

To put everything together, I have assembled a quick example <strong>of</strong> how getaddrinfo() looks in actual<br />

code. Take a look at Listing 4–1.<br />

Listing 4–1. Using getaddrinfo()to Create and Connect a Socket<br />

#!/usr/bin/env python<br />

# <strong>Foundations</strong> <strong>of</strong> <strong>Python</strong> <strong>Network</strong> <strong>Programming</strong> - Chapter 4 - www_ping.py<br />

# Find the WWW service <strong>of</strong> an arbitrary host using getaddrinfo().<br />

import socket, sys<br />

if len(sys.argv) != 2:<br />

» print >>sys.stderr, 'usage: www_ping.py '<br />

» sys.exit(2)<br />

hostname_or_ip = sys.argv[1]<br />

try:<br />

» infolist = socket.getaddrinfo(<br />

» » hostname_or_ip, 'www', 0, socket.SOCK_STREAM, 0,<br />

» » socket.AI_ADDRCONFIG | socket.AI_V4MAPPED | socket.AI_CANONNAME,<br />

» » )<br />

except socket.gaierror, e:<br />

» print 'Name service failure:', e.args[1]<br />

» sys.exit(1)<br />

info = infolist[0] # per standard recommendation, try the first one<br />

socket_args = info[0:3]<br />

address = info[4]<br />

s = socket.socket(*socket_args)<br />

try:<br />

» s.connect(address)<br />

except socket.error, e:<br />

» print '<strong>Network</strong> failure:', e.args[1]<br />

else:<br />

» print 'Success: host', info[3], 'is listening on port 80'<br />

It performs a simple are-you-there test <strong>of</strong> whatever web server you name on the command line by<br />

attempting a quick connection to port 80 with a streaming socket. Using the script would look<br />

something like this:<br />

$ python www_ping.py mit.edu<br />

Success: host WEB.MIT.EDU is listening on port 80<br />

$ python www_ping.py smtp.google.com<br />

<strong>Network</strong> failure: Connection timed out<br />

$ python www_ping.py no-such-host.com<br />

Name service failure: No address associated with hostname<br />

Note three things about the source code.<br />

First, it is completely general, and contains no mention either <strong>of</strong> IP as a protocol nor <strong>of</strong> TCP as a<br />

transport. If the user happened to type a hostname that the system recognized as a host to which it was<br />

connected through AppleTalk (if you can imagine that sort <strong>of</strong> thing in this day and age), then<br />

60

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

Saved successfully!

Ooh no, something went wrong!