Python獲取本地和遠端主機資訊
阿新 • • 發佈:2019-02-03
# -*- coding: cp936 -*-
import socket
print "Creating socket connecting...",
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#把網路服務名(如http,ftp,email)和 協議名(如TCP,UDP,IPX/SPX等)
#轉換為該服務名對應的埠號。如果協議名給定了,則必須為TCP或UDP
#不然將會匹配其他的協議
port = socket.getservbyname("http", "tcp")
print "conection to remote host by port %d" %port
result = s.connect_ex( ("www.baidu.com",port) )
#顯示連結到遠端主機的本地IP地址和埠號
print "Connected from ", s.getsockname()
#x顯示本地IP地址和埠號
print "Connected to ", s.getpeername()
#test
if result != 0 :
print "waiting...."
else :
print "Done .!"
顯示結果如下:
Creating socket connecting... conection to remote host by port 80
Connected from ('192.168.1.102', 54318)
Connected to ('220.181.112.143', 80)
Done .!