判断ip地址是否属于同一网段python,检查ip地址是否属于python中的A,B和C类

该博客介绍了如何在Python中使用`ipaddress`模块来判断一个IPv4地址属于A类、B类还是C类。通过创建IPv4Network对象表示不同类别的地址范围,然后检查给定的IPv4Address是否在这些范围内,可以轻松地判断IP地址的类别。示例代码展示了如何检查特定IP地址是否属于A、B或C类网络。
摘要由CSDN通过智能技术生成

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

解决方案

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值