【Python Network】getaddrinfo处理Family参数

本实例通过命令行取得主机和端口的信息,使用SOCK_STREAM请求一个TCP socket。使用AF_INET或AF_INET6指定协议,但本实例并不指定协议,而是通过查询匹配得出适用的协议。

 1 #! /usr/bin/env python
 2 # Connect Example with IPv4 Awarness - Chapter 5 - ipv4connect.py
 3 
 4 import socket, sys
 5 
 6 def getaddrinfo_pref(host, port, socktype, familypreference = socket.AF_INET):
 7     """Given a host, port and socktype (Usually socket.SOCK_STREAM or 
 8     socket.SOCK_DGRAM), looks up information with both IPv4 and IPv6. If
 9     information is found corresponding to the familypreference, it is returned.
10     Otherwise, any information found is returned. The family preference defaults
11     to IPv4 (socket.AF_INET) but you could also set it to socket.AF_INET6 for IPv6.
12 
13     The return value is the appropriate tuple returned from
14     socket.getaddrinfo()."""
15     
16     results = socket.getaddrinfo(host, port, 0, socktype)
17     for result in results:
18         if result[0] == familypreference:
19             return result
20     return results[0]
21 
22 host = sys.argv[1]
23 port = 'http'
24 
25 c = getaddrinfo_pref(host, port, socket.SOCK_STREAM)
26 print "Connecting to ", c[4]
27 s = socket.socket(c[0], c[1])
28 s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
29 s.connect(c[4])
30 s.sendall("HEAD / HTTP/1.0\r\n\r\n")
31 
32 while 1:
33     buf = s.recv(4096)
34     if not len(buf):
35         break
36     sys.stdout.write(buf)

使用./ipv4connect.py baidu.com运行。截图如下:

posted on 2014-03-11 09:51  Bombe  阅读(292)  评论(0编辑  收藏  举报

导航