# -*- 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和端口号
结果如下:
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]
多次尝试ctrl+b,获得本机的端口号是连续的数字,并非随机分配。
(隔了一会再试会跳几个数,可能是有人也在搞这个吧。。。)
时间: 2024-11-05 16:28:06