python網路編程:socket,gethostname,gethostbyname

來源:互聯網
上載者:User

標籤:

功能:列印主機名稱和主機IP:

[[email protected] python]# cat socket1.py #!/usr/bin/pythonimport sockethost_name = socket.gethostname()print "hostname:%s" % host_nameprint "IP address: %s" %socket.gethostbyname(host_name)

運行結果:

[[email protected] python]# ./socket1.py 
hostname:iZ94gh8l046Z
IP address: 10.170.16.67

模組:

import socket

使用方法:

socket.gethostname擷取hostname(/etc/hostname)

socket.gethostbyname擷取主機IP

改進之後:

[[email protected] python]# cat socket2.py #!/usr/bin/pythonimport socketdef print_machine_info():    host_name = socket.gethostname()    ip_address = socket.gethostbyname(host_name)    print "hostname:%s" % host_name    print "IP address: %s" %ip_addressif __name__ == '__main__':    print_machine_info()

運行結果:

[[email protected] python]# ./socket2.py   
hostname:iZ94gh8l046Z
IP address: 10.170.16.67


說明:我們要在常用的__main__代碼塊中調用這個函數。

運行時,Python會為某些內部變數賦值,例如__name__。在這裡,__name__表示調用程式的進程名。

如果在命令中運行指令碼,__name__的值是__main__

但是,如果在其他指令碼中匯入,情況就不同了。

也就是說,如果在命令列中調用這個模組,會自動運行print_machine_info()函數

如果在其他指令碼中匯入,使用者就要手動調用這個函數。

著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

python網路編程:socket,gethostname,gethostbyname

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.