用於顯示主機名和 IP 地址的 Python 程式?


Python 提供了 gethostname()、 gethostbyname() 兩個函式。gethostname() 檢索本地計算機的標準主機名。gethostbyname() 根據主機名從主機資料庫中檢索主機資訊。

Socket. gethostname()
Socket. gethostbyname()

演算法

Step 1: use module socket.
Step 2: use gethostname() retrives the standard host name for the local machine.
Step 3: use gethostbyname() retrives host information corresponding to a host name from a host database.

示例程式碼

# Display hostname andIP address
import socket
def host_IP():
   try:
      hname = socket.gethostname()
      hip = socket.gethostbyname(hname)
      print("Hostname:  ",hname)
      print("IP Address: ",hip)
   except:
      print("Unable to get Hostname and IP")
# Driver code
host_IP() #Function call

輸出

Hostname:   Satyajit-PC
IP Address:  192.168.1.66

更新於: 30-Jul-2019

1 千+ 次瀏覽

開啟你的 職業生涯

修完課程獲得認證

開始
廣告
© . All rights reserved.