用python写一段代码,随意给两个ip地址和一个子网掩码,判断两个IP地址如果配置该子网掩码,是否属于同一子网(局域网)? 注意:子网掩码不保证是正确的。
时间: 2023-11-27 09:49:32 浏览: 210
以下是实现此功能的 Python 代码:
```python
import ipaddress
def check_same_subnet(ip1, ip2, subnet_mask):
"""
Check if two IP addresses belong to the same subnet.
:param ip1: first IP address
:param ip2: second IP address
:param subnet_mask: subnet mask
:return: True if both IPs belong to the same subnet, False otherwise
"""
ip1 = ipaddress.ip_address(ip1)
ip2 = ipaddress.ip_address(ip2)
subnet_mask = ipaddress.ip_address(subnet_mask)
# Get the network address of the IPs using the subnet mask
net1 = ipaddress.ip_network(str(ip1) + '/' + str(subnet_mask), strict=False)
net2 = ipaddress.ip_network(str(ip2) + '/' + str(subnet_mask), strict=False)
# Compare the network addresses
if net1.network_address == net2.network_address:
return True
else:
return False
```
使用示例:
```python
ip1 = '192.168.1.100'
ip2 = '192.168.1.200'
subnet_mask = '255.255.255.0'
if check_same_subnet(ip1, ip2, subnet_mask):
print('Both IPs belong to the same subnet')
else:
print('Both IPs do not belong to the same subnet')
```
阅读全文