Python IP Doğrulama (IPv4 IPv6 Public Private)

 Python içinde hazır gelen Ipaddress modülü bir IP adresini doğrulamak ve tanımlamak için bize yardımcı olacaktır. IP adresi IPv4, IPv6, Public veya private olabilir. Bu ayrımı küçük bir fonksiyon ile anlayabiliriz.

def validate_ip_address(ip_string):
    try:
        ip_object = ipaddress.ip_address(ip_string)
        if ipaddress.ip_address(ip_string).is_private == False:
            if ip_object.version == 4:
                print("IPv4")
                return "IPv4"
            else:
                print("IPv6")
                return "IPv6"
        else:
            print("The IP address is private")
            return "private"
    except ValueError:
        print("The IP address is not valid")
    return "NotValid"

validate_ip_address(192.168.0.1)

Bir IP adresinin Network IP'sini bulmak istiyorsak aşağıdaki kod bize yardımcı olacaktır.

ip_address=192.168.1.55/24
net_ip=ipaddress.ip_network(ip_address, strict=False)
print(net_ip)

Ayrıntılı bilgi için aşağıdaki adrese göz atabilirsiniz.

ipaddress — IPv4/IPv6 manipulation library

https://docs.python.org/3/library/ipaddress.html

Kaynak kod: https://github.com/python/cpython/blob/3.10/Lib/ipaddress.py

IP versiyon 4 - IP versiyon 6 - Public IP - Private IP 

IP Versiyon kontrolü.

IP bilgileri nasıl listelenir:

-------------------------------------------------
import ipaddress
 
# Initializing an IPv4 Network.
network = ipaddress.IPv4Network("192.168.1.0/24")

print(network)
 
# Network address of the network: 192.168.1.0
print("Network address of the network:", network.network_address)
 
# Broadcast address: 192.168.1.255
print("Broadcast address:", network.broadcast_address)
 
# Network mask: 255.255.255.0
print("Network mask:", network.netmask)
 
# with netmask: 192.168.1.0/255.255.255.0
print("with netmask:", network.with_netmask)
 
# with_hostmask: 192.168.1.0/0.0.0.255
print("with_hostmask:", network.with_hostmask)
 
# Length of network prefix in bits: 24
print("Length of network prefix in bits:", network.prefixlen)
 
# Total number of hosts under the network: 256
print("Total number of hosts under the network:", network.num_addresses)
 
# Overlaps 192.168.0.0/16: True
print("Overlaps 192.168.0.0/16:", network.overlaps(ipaddress.IPv4Network("192.168.0.0/16")))
 
# Supernet: 192.168.0.0/23
print("Supernet:", network.supernet(prefixlen_diff=1))
 
# The network is subnet of 192.168.0.0/16: True
print("The network is subnet of 192.168.0.0/16:",
      network.subnet_of(ipaddress.IPv4Network("192.168.0.0/16")))
 
# The network is supernet of 192.168.0.0/16: False
print("The network is supernet of 192.168.0.0/16:",
      network.supernet_of(ipaddress.IPv4Network("192.168.0.0/16")))
 
# Compare the network with 192.168.0.0/16: 1
print("Compare the network with 192.168.0.0/16:",
      network.compare_networks(ipaddress.IPv4Network("192.168.0.0/16")))


Python

Google