# -*- coding: cp936 -*-socket.getaddrinfo(host, port, family=0, socktype=0, proto=0, flags=0)#根據給定的參數host/port,相應的轉換成一個包含用於建立socket對象的五元組,#參數host為網域名稱,以字串形式給出代表一個IPV4/IPV6地址或者None.#參數port如果字串形式就代表一個服務名,比如“http”"ftp""email"等,或者為數字,或者為None#參數family為地主族,可以為AF_INET ,AF_INET6 ,AF_UNIX.#參數socketype可以為SOCK_STREAM(TCP)或者SOCK_DGRAM(UDP)#參數proto通常為0可以直接忽略#參數flags為AI_*的組合,比如AI_NUMERICHOST,它會影響函數的傳回值#附註:給參數host,port傳遞None時建立在C基礎,通過傳遞NULL。#該函數返回一個五元組(family, socktype, proto, canonname, sockaddr),同時第五個參數sockaddr也是一個二元組(address, port)# Echo server programimport socketimport sysHOST = None # Symbolic name meaning all available interfacesPORT = 50007 # Arbitrary non-privileged ports = Nonefor res in socket.getaddrinfo(HOST, PORT, socket.AF_UNSPEC, socket.SOCK_STREAM, 0, socket.AI_PASSIVE): af, socktype, proto, canonname, sa = res try: #根據getaddrinfo()的返回資訊初始化socket s = socket.socket(af, socktype, proto) except socket.error, err_msg: print err_msg #回顯異常資訊 s = None continue try: #sa是(host,port)的二元組 s.bind(sa) #監聽用戶端請求 s.listen(1) except socket.error, err_msg: print err_msg s.close() s = None continue breakif s is None: print 'could not open socket' sys.exit(1) conn, addr = s.accept()print 'Connected by', addrwhile 1: data = conn.recv(1024)# 2)接受資料 if not data: break conn.send(data)# 3)並返回2中接受到得資料conn.close()# Echo client programimport socketimport sysHOST = 'daring.cwi.nl' # The remote hostPORT = 50007 # The same port as used by the servers = Nonefor res in socket.getaddrinfo(HOST, PORT, socket.AF_UNSPEC, socket.SOCK_STREAM): af, socktype, proto, canonname, sa = res try: s = socket.socket(af, socktype, proto) except socket.error, msg: s = None continue try: s.connect(sa) except socket.error, msg: s.close() s = None continue breakif s is None: print 'could not open socket' sys.exit(1) s.sendall('Hello, world')# 1)發送資料data = s.recv(1024)# 4)接受伺服器回顯的資料s.close()print 'Received', repr(data) #列印輸出