1 import socket, sys 2 3 port = 80 4 host = "www.baidu.com" 5 6 print "Creating socket..." 7 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 8 print "done" 9 10 s.connect((host, port))11 print "OK"12 print "Connected from", s.getsockname()13 print "Connected to", s.getpeername()
可以使用getsocketname()返回本地ip地址与端口号,getpeername()返回服务器ip地址与端口号。