#-*-Coding: cp936-*-socket. getaddrinfo (host, port, family = 0, socktype = 0, proto = 0, flags = 0) # Based on the given parameter host/port, convert to a quintuple that contains the quintuple used to create the socket object. # The host parameter is the domain name and is given as a string representing an IPV4/IPV6 address or None. # The parameter port represents a service name in the string format, such as "http" "ftp" "email", a number, or None # The parameter family is the landlord family, it can be AF_INET, AF_INET6, AF_UNIX. # The socketype parameter can be SOCK_STREAM (TCP) or SOCK_DGRAM (UDP) # The parameter proto is usually 0, which can be ignored directly. # The parameter flags is a combination of AI _ *, such as AI_NUMERICHOST, it will affect the return value of the function # Note: To the parameter hos T, port is based on C when None is passed, and NULL is passed. # This function returns a quintuple (family, socktype, proto, canonname, sockaddr), and the fifth parameter sockaddr is also a binary group (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: # initialize socket s = socket according to the response information of getaddrinfo. socket (af, socktype, proto) blocks t socket. error, err_msg: print err_msg # echo exception information s = None continue try: # sa is the Binary Group s of (host, port. bind (sa) # Listen to the client request s. listen (1) blocks t 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 'connectedby', addrwhile 1: data = conn. recv (1024) #2) Accept data if not data: break conn. send (data) #3) and return the data conn received in 2. 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) blocks t socket. error, msg: s = None continue try: s. connect (sa) using t 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) send data = s. recv (1024) #4) Accept the server echo data s. close () print 'received', repr (data) # print the output