network
IP and subnet helpers built on the standard library ipaddress module.
Examples:
>>> from ures.network import verify_ip_in_subnet
>>> verify_ip_in_subnet("192.168.1.10", "192.168.1.0/24")
True
verify_ip_in_subnet
verify_ip_in_subnet(ip: str, subnet: str) -> bool
Check if a given IP address belongs to a specified subnet.
This function converts the provided IP address and subnet (in CIDR notation) into their respective ipaddress objects, then checks if the IP address is within the network defined by the subnet.
Parameters:
-
ip(str) –The IP address to check (e.g., "192.168.1.10").
-
subnet(str) –The subnet in CIDR notation (e.g., "192.168.1.0/24").
Returns:
-
bool(bool) –True if the IP address is within the subnet, False otherwise.
Examples:
>>> verify_ip_in_subnet("192.168.1.10", "192.168.1.0/24")
True
>>> verify_ip_in_subnet("10.0.0.1", "192.168.1.0/24")
False
Source code in ures/network.py
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | |
is_valid_ip_netmask
is_valid_ip_netmask(ip: str, netmask: str) -> bool
Validate whether an IP address and a given subnet mask form a valid subnet.
This function checks if the provided IP address (IPv4 or IPv6) and its subnet mask (provided either in CIDR notation or dot-decimal format for IPv4) are valid when used together to define a network.
Parameters:
-
ip(str) –The IP address (e.g., "192.168.1.1" or "2001:db8::1").
-
netmask(str) –The subnet mask, which can be provided as a CIDR value (e.g., "24") or in dot-decimal format (e.g., "255.255.255.0" for IPv4).
Returns:
-
bool(bool) –True if the IP address and subnet mask form a valid subnet, False otherwise.
Examples:
>>> is_valid_ip_netmask("192.168.1.1", "255.255.255.0")
True
>>> is_valid_ip_netmask("192.168.1.1", "24")
True
>>> is_valid_ip_netmask("2001:db8::1", "64")
True
>>> is_valid_ip_netmask("192.168.1.1", "255.255.0.255")
False
>>> is_valid_ip_netmask("300.168.1.1", "24")
False
Source code in ures/network.py
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 | |
generate_ip
generate_ip(subnet: str, last_index: int) -> str
Generate a new IP address within a given subnet based on an offset.
The function adds the provided 'last_index' to the network address of the specified subnet (given in CIDR notation) to compute a new IP address.
Parameters:
-
subnet(str) –The subnet in CIDR notation (e.g., "192.168.0.0/24").
-
last_index(int) –The offset to add to the network address.
Returns:
-
str(str) –The generated IP address as a string.
Examples:
>>> generate_ip("192.168.0.0/24", 100)
'192.168.0.100'
Source code in ures/network.py
85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 | |