Erle Robotics Python Networking Gitbook Free

getaddrinfo() in your own code

Here you have a quick example of how getaddrinfo() looks in actual code in

import socket, sys

if len(sys.argv) != 2:
    print >>sys.stderr, 'usage: <hostname_or_ip>'

hostname_or_ip = sys.argv[1]

    infolist = socket.getaddrinfo(
        hostname_or_ip, 'www', 0, socket.SOCK_STREAM, 0,
        socket.AI_ADDRCONFIG | socket.AI_V4MAPPED | socket.AI_CANONNAME,
except socket.gaierror, e:
    print 'Name service failure:', e.args[1]

info = infolist[0]  # per standard recommendation, try the first one
socket_args = info[0:3]
address = info[4]
s = socket.socket(*socket_args)
except socket.error, e:
    print 'Network failure:', e.args[1]
    print 'Success: host', info[3], 'is listening on port 80'
It performs a simple are-you-there test of whatever web server you name on the command line by

attempting a quick connection to port 80 with a streaming socket. Using the script would look something like this:

[email protected]:~/Python_files#
[email protected]:~/Python_files# python
Success: host is listening on port 80
[email protected]:~/Python_files# python
Name service failure: nodename nor servname provided, or not known
[email protected]:~/Python_files#
Name service failure: nodename nor servname provided, or not known
[email protected]:~/Python_files#

Note that the socket()constructor does not take a list of three items as its parameter. Instead, the parameter list is introduced by an asterisk, which means that the three elements of the socket_args list are passed as three separate parameters to the constructor.