check if ip address belongs to a Class A, B and C in python

[亡魂溺海] 提交于 2020-05-15 10:46:05

问题


How can determine class of IP address in python. I am working with ipaddress module of python. Following are class definitions

Class   Private Networks    Subnet Mask Address Range
A   10.0.0.0    255.0.0.0   10.0.0.0 - 10.255.255.255
B   172.16.0.0 - 172.31.0.0 255.240.0.0 172.16.0.0 - 172.31.255.255
C   192.168.0.0 255.255.0.0 192.168.0.0 - 192.168.255.255

Given a IP how can I check if it belongs to Class A, B or C


回答1:


IPv4

Use ipaddress.IPv4Address and ipaddress.IPv4Network types.

from ipaddress import IPv4Address, IPv4Network

classA = IPv4Network(("10.0.0.0", "255.0.0.0"))  # or IPv4Network("10.0.0.0/8")
classB = IPv4Network(("172.16.0.0", "255.240.0.0"))  # or IPv4Network("172.16.0.0/12")
classC = IPv4Network(("192.168.0.0", "255.255.0.0"))  # or IPv4Network("192.168.0.0/16")

I gave you the tuple form as you have the network address and mask but if you prefer the /X (CIDR standard) suffix it also accepts it. There are actually some additional ways.

To use it you will just check if a certain IPv4Address is in the IPv4Network as if you were checking in an element is found inside a list:

ip1 = IPv4Address("10.0.2.8")
ip2 = IPv4Address("172.18.76.25")
ip3 = IPv4Address("192.168.45.62")

ip1 in classA  # True
ip2 in classA  # False
ip3 in classA  # False

ip1 in classB  # False
ip2 in classB  # True
ip3 in classB  # False

ip1 in classC  # False
ip2 in classC  # False
ip3 in classC  # True

IPv6

Use ipaddress.IPv6Address and ipaddress.IPv6Network types instead and correct IPv6 ip strings when creating the objects.

Generic

If both supporting IPv4 and IPv6 is desired, ipaddress.ip_address and ipaddress.ip_network convenience factory functions can be used, and the module will create the appropiate IPv4 or IPv6 class depending on the string format.


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



来源:https://stackoverflow.com/questions/42385097/check-if-ip-address-belongs-to-a-class-a-b-and-c-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!