Code listing 4-1 Creating and connecting Sockets using Getaddrinfo ()
Importargparse, socket, sysdefconnect_to (hostname_or_ip):Try: Infolist= Socket.getaddrinfo (Hostname_or_ip,'www', 0, socket. Sock_stream, 0, socket. Ai_addrconfig | Socket. ai_v4mapped |socket. Ai_canonname)#getaddrinfo () requests a possible way to connect to the HTTP service provided by HOSTNAME_OR_IP, returning a method that can provide a link #Ai_addrconfig tags to filter out all addresses that the computer cannot connect to #ai_v4mapped, re-encode the IPV4 address as a IPV6 address that can be actually used #ai_cannonname, reverse query, returns the fourth item in the tuple that contains the canonical host name exceptSocket.gaierror as E:Print('Name service failure:', e.args[1]) Sys.exit (1) Info= Infolist[0]#returns the first item in the tuple listSocket_args = Info[0:3]#Protocol FamilyAddress = Info[4]#Canonical host names = Socket.socket (*Socket_args)Try: S.connect (address)exceptSocket.error as E:Print('Network Failure:', e.args[1]) Else: Print('Success:host', Info[3],'is listening on port.')if __name__=='__main__': Parser= Argparse. Argumentparser (Description ='Try connecting to Port') parser.add_argument ('hostname', help='hostname This want to the contact') connect_to (Parser.parse_args (). hostname)
The getaddrinfo () function is used to convert a user-specified host name and port number to an important method that is required for the address used by the socket method. For example, use getaddrinfo () to get a method that Baidu.com provides HTTP services:
Import= socket.getaddrinfo ('baidu.com','www' ) Infolist
return results
", ('111.13.101.208',"),('), (' 123.125.114.144', ()), (', ', ('220.181.57.217' ) , 80))]
From the return results can be seen, provide 3 methods to connect baidu.com HTTP service, the protocol family is af_inet (protocol code is 2), datagram type Sock_stream (Protocol code 1), the third item 0 means wildcard character (?). ), the fourth is the canonical hostname, followed by the two-tuple of the IP address and port number.
Instead of passing three separate parameters to the socket function, the program uses an asterisk to pass in the list, indicating that 3 elements in the Socket_args table are passed into the constructor as three parameters.
Python Network Programming Learning Note (iii)--socket name and DNS