检查ip地址是否属于python中的A,B和C类 [英] check if ip address belongs to a Class A, B and C in python

查看:116
本文介绍了检查ip地址是否属于python中的A,B和C类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在python中确定IP地址的类别.我正在使用python的ipaddress模块​​. 以下是类定义

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

给出IP,如何检查它是否属于A,B或C类?

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

推荐答案

IPv4

使用ipaddress.IPv4Addressipaddress.IPv4Network类型.

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")

我给了您元组形式,因为您具有网络地址和掩码,但是如果您更喜欢/X(CIDR标准)后缀,它也可以接受.实际上,还有其他一些方法.

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.

要使用它,您只需检查某个IPv4Address是否为in IPv4Network,就像您正在检查元素一样,可以在list中找到

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

改用ipaddress.IPv6Addressipaddress.IPv6Network类型,并在创建对象时更正IPv6 ip字符串.

IPv6

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

如果需要同时支持IPv4和IPv6,则可以使用ipaddress.ip_addressipaddress.ip_network便利工厂功能,并且该模块将根据字符串格式创建适当的IPv4或IPv6类.

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.

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

这篇关于检查ip地址是否属于python中的A,B和C类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆