Python的socket模塊提供了類(lèi)的方法和實(shí)例方法,二者區(qū)別在于使用類(lèi)方法時(shí)不需要?jiǎng)?chuàng)建套接字對(duì)象實(shí)例。比如,以下例子利用此模塊獲取主機(jī)名和ip地址。
源代碼如下
#!/usr/bin/env python #This program is optimized for python 2.7 .It may run on any #other python version with/without modifications. #Failname:local_machine_info.py import socket def print_machine_info(): host_name=socket.gethostname() ip_address=socket.gethostbyname(host_name) print "Host name : %s" %host_name print "IP address: %s" %ip_address if __name__=='__main__': print_machine_info()
執(zhí)行結(jié)果:
原理分析:
本例程調(diào)用了socket中的兩個(gè)工具函數(shù)gethostname()和gethostbyname()。可以使用help()函數(shù)查看幫助信息。
獲取遠(yuǎn)程設(shè)備的IP地址
使用內(nèi)置的庫(kù)函數(shù)gethostbyname()可以獲取遠(yuǎn)程設(shè)備的ip地址,函數(shù)的參數(shù)為目標(biāo)主機(jī)的主機(jī)名。
以遠(yuǎn)程主機(jī)名為www.51cto.com為例,代碼如下:
#!/usr/bin/env python #This program is optimized for python 2.7 #It may run on any other version with/without modifications #Filename:remote_machine_info.py import socket def get_remote_matchine_info(): remote_host='www.51cto.com' try: print " remote_host is:%s"%remote_host print "IP address:%s"%socket.gethostbyname(remote_host) except socket.error,err_msg: print "%s:%s"%(remote_host,err_msg) if __name__=='__main__': get_remote_matchine_info()
執(zhí)行結(jié)果:
原理分析:
本例將主要的函數(shù)調(diào)用放在了try-except塊中,如果gethostbyname()函數(shù)執(zhí)行的過(guò)程中發(fā)送了錯(cuò)誤,這個(gè)錯(cuò)誤將由try-except塊處理,提示錯(cuò)誤信息。
另外有需要云服務(wù)器可以了解下創(chuàng)新互聯(lián)scvps.cn,海內(nèi)外云服務(wù)器15元起步,三天無(wú)理由+7*72小時(shí)售后在線,公司持有idc許可證,提供“云服務(wù)器、裸金屬服務(wù)器、高防服務(wù)器、香港服務(wù)器、美國(guó)服務(wù)器、虛擬主機(jī)、免備案服務(wù)器”等云主機(jī)租用服務(wù)以及企業(yè)上云的綜合解決方案,具有“安全穩(wěn)定、簡(jiǎn)單易用、服務(wù)可用性高、性價(jià)比高”等特點(diǎn)與優(yōu)勢(shì),專(zhuān)為企業(yè)上云打造定制,能夠滿足用戶豐富、多元化的應(yīng)用場(chǎng)景需求。