Socket.getaddrinfo (host, Port, Family=0, Socktype=0, proto=0, flags=0) #根据给定的参数host/port, converted to a five-tuple containing the socket object.
#参数host为域名, given as a string to represent an Ipv4/ipv6 address or none.
#参数port如果字符串形式就代表一个服务名, such as "http" "FTP" "email" and so on, or for the number, or none #参数family为地主族, can be af_inet, Af_inet6, Af_unix.
#参数socketype可以为SOCK_STREAM (TCP) or Sock_dgram (UDP) #参数proto通常为0可以直接忽略 a combination of #参数flags为AI_ *, such as ai_numerichost, that affects the return value of a function
#附注: Host,port The parameter to pass none is based on C, passing null.
#该函数返回一个五元组 (family, Socktype, Proto, Canonname, sockaddr), while the fifth parameter sockaddr is also a two-tuple (address, port) # Echo Server program Import Socket Import sys HOST = None # symbolic name meaning all available interfaces PORT = 8888
# arbitrary non-privileged Port s = None for res in Socket.getaddrinfo (HOST, Port, Socket.af_unspec, Socket. Sock_stream, 0, socket. ai_passive): AF, Socktype, Proto, canonname, sa = res try: #根据getaddrinfo () return information Initialize socket s = Sock Et.socket (AF, Socktype, proto) except Socket.error, Err_msg:print err_msg #回显异常信息 s = None continue try: #sa是 (host,port) two-tuple s.b
IND (SA) #监听客户端请求 S.listen (1) except Socket.error, Err_msg:print err_msg s.close () s = None Continue break if s. None:print ' could not open socket ' sys.exit (1) conn, addr = S.accept () print ' Connected by ', addr while 1:data = CONN.RECV (1024) # 2) Accept data if not data:break Conn.send (d ATA) # 3) and returns the received data in 2 Conn.close () # Echo client program import socket import sys HOST = ' 127.0.0.1 ' # The remote hos T port = 8888 # The same port as used by the server S = None for 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) exc
Ept socket.error, msg:s = None continue try:s.connect (sa) except Socket.error, msg: S. Close () s = None Continue break if s none:print ' could not open socket ' sys.exit (1) S.sendall (' Hello, World ') # 1 sends data = S.RECV (1024) # 4) accepts server-echo data s.close () print ' Received ', repr (data) #打印输出