Python - 从主机名获取 IP 地址

Python 接口模块可以用来从主机名中获取 IP 地址。

插槽模块是Python核心库的一部分,所以我们不需要单独安装。

Python Socket 模块可以从 Hostname 获取 IP 地址

Python 接口模块 gethostbyname() 函数接受主机名参数并以字符串格式返回 IP 地址。

以下是一個簡單的例子,用Python解釋器來找出某些網站的IP地址。

 1# python3.7
 2Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 16:52:21) 
 3[Clang 6.0 (clang-600.0.57)] on darwin
 4Type "help", "copyright", "credits" or "license" for more information.
 5>>> 
 6>>> import socket
 7>>> socket.gethostbyname('journaldev.com')
 8'45.79.77.230'
 9>>> socket.gethostbyname('google.com')
10'172.217.166.110'
11>>>

** 注意**:如果网站在负载平衡器后面或在云中工作,您可能会收到 IP 地址搜索的不同结果。

例如,尝试为 google.com 或 facebook.com 运行上述命令. 如果您不在与我的 (印度) 相同的位置,很可能您将获得不同的 IP 地址作为输出。

Python Script 来找出网站的 IP 地址

让我们看看一个例子,我们要求用户输入网站地址,然后打印其IP地址。

1import socket
2
3hostname = input("Please enter website address:\n")
4
5# IP lookup from hostname
6print(f'The {hostname} IP Address is {socket.gethostbyname(hostname)}')

Python Get Ip Address Hostname

以下是将主机名作为命令行参数(/community/tutorials/python-command-line-arguments)传递给脚本的另一个示例。

1import socket
2import sys
3
4# no error handling is done here, excuse me for that
5hostname = sys.argv[1]
6
7# IP lookup from hostname
8print(f'The {hostname} IP Address is {socket.gethostbyname(hostname)}')

出发点:

1# python3.7 ip_address.py facebook.com
2The facebook.com IP Address is 157.240.23.35

使用 socket.gethostbyname( )的错误场景

如果主機名稱無法解決到有效的 IP 位址,就會出現「socket.gaierror」。我們可以在我們的程式中使用 try-except區塊來捕捉這個錯誤。

以下是对无效主机名进行例外处理的更新脚本。

 1import socket
 2import sys
 3
 4hostname = sys.argv[1]
 5
 6# IP lookup from hostname
 7try:
 8    ip = socket.gethostbyname(hostname)
 9    print(f'The {hostname} IP Address is {ip}')
10except socket.gaierror as e:
11    print(f'Invalid hostname, error raised is {e}')

输出:

1# python3.7 ip_address.py jasjdkks.com               
2Invalid hostname, error raised is [Errno 8] nodename nor servname provided, or not known
3#

** 参考**: Socket Module API Docs

Published At
Categories with 技术
Tagged with
comments powered by Disqus