#-*-Coding:utf-8-*-import socketprint "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 Portprint " done\n "print" Connecting to remote host ... "S.connect ((" www.baidu.com ", port) print" done\n "print" conneted from ", S.getsockname () #获得本地机器的ip和端口号 (the port number is randomly assigned by the operating system and is different every time) print "conneted to", S.getpeername () #获得连接机器的ip和端口号
The results are as follows:
Creating socket
done!
Looking up port number ...
80
Done
Connecting to remote host ...
Done
Conneted from (' 122.207.52.35 ', 56207)
conneted to (' 119.75.217.109 ', 80)
[Finished in 0.3s]
Try ctrl+b multiple times, get the port number of the machine is a continuous number, not randomly assigned.
(After a while, try to jump a few numbers, maybe someone is doing this ...) )
"Python" Socket Network programming