This function allows you to check if an IP belongs to a network subnet Example: returns True if ip = 192.168.1.1 and net = 192.168.1.0/24 returns False if ip = 192.168.1.1 and net = 192.168.100.0/24 :rtype: bool
(ip: str, net: str)
| 724 | |
| 725 | |
| 726 | def address_in_network(ip: str, net: str) -> bool: |
| 727 | """This function allows you to check if an IP belongs to a network subnet |
| 728 | |
| 729 | Example: returns True if ip = 192.168.1.1 and net = 192.168.1.0/24 |
| 730 | returns False if ip = 192.168.1.1 and net = 192.168.100.0/24 |
| 731 | |
| 732 | :rtype: bool |
| 733 | """ |
| 734 | ipaddr = struct.unpack("=L", socket.inet_aton(ip))[0] |
| 735 | netaddr, bits = net.split("/") |
| 736 | netmask = struct.unpack("=L", socket.inet_aton(dotted_netmask(int(bits))))[0] |
| 737 | network = struct.unpack("=L", socket.inet_aton(netaddr))[0] & netmask |
| 738 | return (ipaddr & netmask) == (network & netmask) |
| 739 | |
| 740 | |
| 741 | def dotted_netmask(mask: int) -> str: |