Python程式用於查詢客戶端的IP地址


在本教程中,我們將使用Python中的socket模組來查詢客戶端的IP地址。每檯筆記本電腦、手機、平板電腦等都擁有其獨特的IP地址。我們將使用socket模組來查詢它。讓我們看看查詢裝置IP地址的步驟。

演算法

  1. 匯入socket模組
  2. 使用socket.gethostname()方法獲取主機名並將其儲存在一個變數中。
  3. 透過將主機名作為引數傳遞給
  4. socket.gethostbyname()方法來查詢IP地址,並將其儲存在一個變數中。
  5. 列印IP地址。

讓我們為上述演算法編寫程式碼。

示例

線上演示

## importing socket module
import socket
## getting the hostname by socket.gethostname() method
hostname = socket.gethostname()
## getting the IP address using socket.gethostbyname() method
ip_address = socket.gethostbyname(hostname)
## printing the hostname and ip_address
print(f"Hostname: {hostname}")
print(f"IP Address: {ip_address}")

輸出

如果您執行上述程式,您將得到以下輸出。

Hostname: DESKTOP-A0PM5GD
IP Address: 192.168.43.15

結論

如果您對本教程有任何疑問,請在評論區提出。

更新於:2023年8月25日

57K+ 次瀏覽

開啟你的職業生涯

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.