#!/usr/bin/env python # Information Example - Chapter 2 import socket print"Creating socket", s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) print"done." print"Looking up port number", port = socket.getservbyname('http', 'tcp') print"done." print"Connecting to remote host on port %d"% port, s.connect(("www.google.com", port)) print"done." print"Connected from", s.getsockname() print"Connected to", s.getpeername()
输出结果会显示:
Creating socket... done.
Looking up port number... done.
Connecting to remote host on port 80... done.
Connected from ('192.168.XX.XX', 2548)
Connected to ('64.233.189.104', 80)
可以看到,我的本机使用的是一个随机的端口号(2548),每次执行端口号都会不同。
4. File-like 对象
我们可以通过Socket对象来执行一些比如发送(send(), sendto()),接收数据的操作(recv(), recvfrom()),同时,我们还可以把Socket对象转换为一个类似文件的对象(File-like Object),然后使用其中的write()来发送数据,read(), readline()来接收数据。
File-like对象更适合TCP连接,因为TCP连接必须保证数据流能够完整正确的到达,数据流表现的更像是一个文件。而UDP却不是,它是一个基于包的连接,它只管把这些包发送出去,如果使用File-like对象来处理,将很难追踪定位出现的错误。生成一个File-like对象通过下面的语句:
import sys, socket def getipaddrs(hostname): """Get a list of IP addresses from a given hostname. This is a standard (forward) lookup.""" result = socket.getaddrinfo(hostname, None, 0, socket.SOCK_STREAM) return [x[4][0] for x in result] def gethostname(ipaddr): """Get the hostname from a given IP address. This is a reverse lookup.""" return socket.gethostbyaddr(ipaddr)[0] try: # First, do the reverse lookup and get the hostname. hostname = gethostname(sys.argv[1]) # could raise socket.herror # Now, do a forward lookup on the result from the earlier reverse # lookup. ipaddrs = getipaddrs(hostname) # could raise socket.gaierror except socket.herror, e: print"No host names available for %s; this may be normal."% sys.argv[1] sys.exit(0) except socket.gaierror, e: print"Got hostname %s, but it could not be forward-resolved: %s"% \ (hostname, str(e)) sys.exit(1) # If the forward lookup did not yield the original IP address anywhere, # someone is playing tricks. Explain the situation and exit. ifnot sys.argv[1] in ipaddrs: print"Got hostname %s, but on forward lookup,"% hostname print"original IP %s did not appear in IP address list."% sys.argv[1] sys.exit(1) # Otherwise, show the validated hostname. print"Validated hostname:", hostname