#-*-Coding: cp936-*-import socketprint "Creating socket connecting... ", s = socket. socket (socket. AF_INET, socket. SOCK_STREAM) # convert the network service name (such as http, ftp, email) and Protocol name (such as TCP, UDP, IPX/SPX) # To the port number corresponding to the service name. If the protocol name is specified, it must be TCP or UDP # Otherwise it will match other protocol port = socket. getservbyname ("http", "tcp") print "conection to remote host by port % d" % port result = s. connect_ex ("www.baidu.com", port) # display the local IP address and port number that link to the remote host print "Connected from", s. getsockname () # x displays the local IP address and port number print "Connected to", s. getpeername () # testif result! = 0: print "waiting..." else: print "Done .! "
The result is as follows:
Creating socket connecting... conection to remote host by port 80
Connected from ('192. 168.1.102 ', 192)
Connected to ('192. 181.112.143 ', 80)
Done .!