# -*- coding: utf-8 -*- import socket print "Creating socket" s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) print "Done!\n" print 'Looking up port number...' port = socket.getservbyname('http','tcp') print port print "Done\n" print "Connecting to remote host..." s.connect(("www.baidu.com", port)) print "Done\n" print "Conneted from",s.getsockname() #得到本地機器的ip和端口號(端口號由操做系統隨機分配,每次都不同) print "Conneted to",s.getpeername() #得到鏈接機器的ip和端口號
結果以下:python
Creating socketsocket
Done!tcp
Looking up port number...操作系統
80code
Doneip
Connecting to remote host...utf-8
Donerem
Conneted from ('122.207.52.35', 56207)get
Conneted to ('119.75.217.109', 80)class
[Finished in 0.3s]
屢次嘗試ctrl+b,得到本機的端口號是連續的數字,並不是隨機分配。
(隔了一會再試會跳幾個數,多是有人也在搞這個吧。。。)