了解最新公司动态及行业资讯
IP 地址和网络密不可分,Python 的ipaddress模块可以帮助处理各种 IP 相关任务。它可以检查 IP 是否为私有地址,验证地址,并执行子网计算。socket模块有助于解析主机名,而subprocess模块允许 ping 操作和网络诊断。本文涵盖了 Python 中的关键 IP 操作,包括:检查 IP 是否为私有,从 IP 获取主机名,ping 主机,处理 ping 超时以及与子网一起工作。
一些 IP 地址是为内部网络设计的。它们不在互联网上路由。这些私有范围是:
10.0.0.0–10.255.255.255 172.16.0.0–172.31.255.255 172.16.0.0–172.31.255.255 192.168.0.0–192.168.255.255Python 使用 ipaddress 使检查 IP 地址变得简单。下面的示例确定一个 IP 地址是否属于私有范围。
import ipaddressdef check_private_ip(ip):try:ip_obj = ipaddress.ip_address(ip)return ip_obj.is_privateexcept ValueError:return Falseip = "192.168.0.1"print(f"Is {ip} private? {check_private_ip(ip)}")如果 IP 在私有范围内,函数返回True。否则,返回False。这有助于过滤内部和外部 IP。
一个无效的 IP 地址可能导致脚本出错。Python 允许轻松验证。如果 IP 格式不正确,ipaddress模块将引发异常。
def validate_ip(ip):try:ipaddress.ip_address(ip)return Trueexcept ValueError:return Falseprint(validate_ip("256.100.50.25"))# Invalid IP, returns Falseprint(validate_ip("192.168.1.1"))# Valid IP, returns True此功能防止无效 IP 在网络操作中使用。
域名系统(DNS)将 IP 地址转换为主机名。Python 的socket模块从 IP 地址检索主机名。
import socketdef get_hostname(ip):try:return socket.gethostbyaddr(ip)[0]except socket.herror:return "Hostname not found"print(get_hostname("8.8.8.8"))# Googles public DNS此函数将 IP 地址解析为域名(如果存在的话)。
主机名映射到 IP 地址。`socket`模块帮助将域名解析为其 IP 地址。
def get_ip_from_hostname(hostname):try:return socket.gethostbyname(hostname)except socket.gaierror:return "Invalid hostname"print(get_ip_from_hostname("google.com"))如果该域名存在,则函数返回其对应的 IP。
pinging 检查主机是否可达。Python 的子进程模块允许执行系统命令,包括ping。
import subprocessdef ping_host(host):try:output = subprocess.run(["ping", "-c", "1", host], capture_output=True, text=True)return output.returncode == 0except Exception:return Falseprint(ping_host("8.8.8.8"))# Returns True if reachable此函数运行单个 ping 请求。如果返回码为0,则表示主机可达。
网络速度慢可能会延迟响应。超时可以避免长时间等待。
def ping_with_timeout(host, timeout=2):try:output = subprocess.run(["ping", "-c", "1", "-W", str(timeout), host], capture_output=True, text=True)return output.returncode == 0except Exception:return Falseprint(ping_with_timeout("8.8.8.8", timeout=1))# Adjust timeout as needed此函数确保在给定时间内收到 ping 响应。
子网将 IP 地址分组。`ipaddress`模块检查一个 IP 地址是否属于某个子网。
def check_ip_in_subnet(ip, subnet):try:return ipaddress.ip_address(ip) in ipaddress.ip_network(subnet, strict=False)except ValueError:return Falseprint(check_ip_in_subnet("192.168.1.100", "192.168.1.0/24"))# Trueprint(check_ip_in_subnet("192.168.2.100", "192.168.1.0/24"))# False此函数有助于确定一个 IP 地址是否属于特定网络。
子网包含多个 IP 地址。Python 可以列出范围内的所有 IP 地址。
def list_ips_in_subnet(subnet):try:return [str(ip) for ip in ipaddress.ip_network(subnet, strict=False)]except ValueError:return []print(list_ips_in_subnet("192.168.1.0/30"))此函数返回子网内的所有 IP 地址,用于扫描网络。