一文学会使用Python中的IP地址操作

自由坦荡的智能 2025-03-12 01:22:53

IP 地址和网络密不可分,Python 的ipaddress模块可以帮助处理各种 IP 相关任务。它可以检查 IP 是否为私有地址,验证地址,并执行子网计算。socket模块有助于解析主机名,而subprocess模块允许 ping 操作和网络诊断。本文涵盖了 Python 中的关键 IP 操作,包括:检查 IP 是否为私有,从 IP 获取主机名,ping 主机,处理 ping 超时以及与子网一起工作。

检查 IP 地址是否为私有

一些 IP 地址是为内部网络设计的。它们不在互联网上路由。这些私有范围是:

10.0.0.0–10.255.255.255172.16.0.0–172.31.255.255 172.16.0.0–172.31.255.255192.168.0.0–192.168.255.255

Python 使用 ipaddress 使检查 IP 地址变得简单。下面的示例确定一个 IP 地址是否属于私有范围。

import ipaddressdef check_private_ip(ip): try: ip_obj = ipaddress.ip_address(ip) return ip_obj.is_private except ValueError: return Falseip = "192.168.0.1"print(f"Is {ip} private? {check_private_ip(ip)}")

如果 IP 在私有范围内,函数返回True。否则,返回False。这有助于过滤内部和外部 IP。

验证 IP 地址

一个无效的 IP 地址可能导致脚本出错。Python 允许轻松验证。如果 IP 格式不正确,ipaddress模块将引发异常。

def validate_ip(ip): try: ipaddress.ip_address(ip) return True except ValueError: return Falseprint(validate_ip("256.100.50.25")) # Invalid IP, returns Falseprint(validate_ip("192.168.1.1")) # Valid IP, returns True

此功能防止无效 IP 在网络操作中使用。

获取 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")) # Google's public DNS

此函数将 IP 地址解析为域名(如果存在的话)。

查找主机名的 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。

正在 ping 主机

pinging 检查主机是否可达。Python 的子进程模块允许执行系统命令,包括ping。

import subprocessdef ping_host(host): try: output = subprocess.run(["ping", "-c", "1", host], capture_output=True, text=True) return output.returncode == 0 except Exception: return Falseprint(ping_host("8.8.8.8")) # Returns True if reachable

此函数运行单个 ping 请求。如果返回码为0,则表示主机可达。

设置 ping 超时

网络速度慢可能会延迟响应。超时可以避免长时间等待。

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 == 0 except Exception: return Falseprint(ping_with_timeout("8.8.8.8", timeout=1)) # Adjust timeout as needed

此函数确保在给定时间内收到 ping 响应。

检查 IP 是否属于子网

子网将 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 列表

子网包含多个 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 地址,用于扫描网络。

0 阅读:1

自由坦荡的智能

简介:感谢大家的关注