Python網絡編程——獲取遠程設備的IP地址


有時需要把設備的主機名轉換成對應的IP地址,下面是一個簡單的操作。

 1 import socket
 2 
 3 
 4 def get_remote_machine_info():  # 定義get_remote_machine_info()函數
 5     remote_host = 'www.python.org'  # 定義遠程設備名稱
 6     try:  # try-except塊
 7         print("IP address of %s: %s" % (remote_host, socket.gethostbyname(remote_host)))
 8         # 打印遠端設備名稱及對應的IP地址
 9     except socket.error as err_msg:    # 如果IP地址沒有獲取成功,則打印對應的錯誤消息
10         print("%s: %s" % (remote_host, err_msg))
11 
12 
13 if __name__ == '__main__':
14     get_remote_machine_info()

運行結果:

1.域名正確返回對應的IP地址

$ python3 1_2_remote_machine_info.py

IP address of www.python.org: 151.101.16.223

2.域名錯誤無法返回IP地址(將www.python.org更改為www.pyon.org),提示對應的錯誤

1 $ python3 1_2_remote_machine_info.py
2 www.pyon.org: [Errno 8] nodename nor servname provided, or not known

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM