Python –从主机名获取IP地址

时间:2020-02-23 14:42:45  来源:igfitidea点击:

Python套接字模块可用于从主机名获取IP地址。

套接字模块是Python核心库的一部分,因此我们不需要单独安装。

Python套接字模块从主机名获取IP地址

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

这是Python解释器中的一个简单示例,用于查找某些的IP地址。

# python3.7
Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 16:52:21) 
[Clang 6.0 (clang-600.0.57)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> 
>>> import socket
>>> socket.gethostbyname('theitroad.local')
'45.79.77.230'
>>> socket.gethostbyname('google.com')
'172.217.166.110'
>>> 

注意:如果在负载均衡器后面或者在云中运行,则IP地址查找可能会得到不同的结果。

例如,尝试对google.com或者facebook.com运行以上命令。
如果您与我的位置不同(旧金山),则可能会获得不同的IP地址作为输出。

Python脚本找出的IP地址

让我们看一个示例,在该示例中,要求用户输入地址,然后打印其IP地址。

import socket

hostname = input("Please enter website address:\n")

# IP lookup from hostname
print(f'The {hostname} IP Address is {socket.gethostbyname(hostname)}')

Python从主机名获取IP地址

这是另一个将主机名作为命令行参数传递给脚本的示例。
该脚本将找到IP地址并进行打印。

import socket
import sys

# no error handling is done here, excuse me for that
hostname = sys.argv[1]

# IP lookup from hostname
print(f'The {hostname} IP Address is {socket.gethostbyname(hostname)}')

输出:

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

socket.gethostbyname()的错误方案

如果主机名无法解析为有效的IP地址,则会引发" socket.gaierror"。
我们可以使用try-except块在程序中捕获此错误。

这是更新的脚本,其中包含对无效主机名的异常处理。

import socket
import sys

hostname = sys.argv[1]

# IP lookup from hostname
try:
  ip = socket.gethostbyname(hostname)
  print(f'The {hostname} IP Address is {ip}')
except socket.gaierror as e:
  print(f'Invalid hostname, error raised is {e}')

输出:

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