Computer >> Máy Tính >  >> Lập trình >> Python

Chương trình Python để hiển thị tên máy chủ và địa chỉ IP?

Python cung cấp hai hàm gethostname (), gethostbyname (). gethostname () truy xuất lại tên máy chủ lưu trữ chuẩn cho máy cục bộ. gethostbyname () truy xuất lại thông tin máy chủ tương ứng với tên máy chủ từ cơ sở dữ liệu máy chủ.

Ổ cắm
Socket. gethostname()
Socket. gethostbyname()

Thuật toán

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.

Mã mẫu

# 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

Đầu ra

Hostname:   Satyajit-PC
IP Address:  192.168.1.66