在给定 IP 和子网掩码时确定网络 IP

Determine Network IP when given an IP and subnet mask

在Python中,如果我有IP地址和子网掩码字符串,如何确定网络IP?

即IP = 10.0.0.20,掩码 = 255.255.255.0 将导致网络 IP 为 10.0.0.0

模块 ipcalc 可以快速处理 ip 地址作为字符串:

代码:

import ipcalc

addr = ipcalc.IP('10.0.0.20', mask='255.255.255.0')
network_with_cidr = str(addr.guess_network())
bare_network = network_with_cidr.split('/')[0]

print(addr, network_with_cidr, bare_network)

结果:

IP('10.0.0.20/24') '10.0.0.0/24' '10.0.0.0'

好吧,我应该 post 我所做的..它对我的目的有效:

# Return the network of an IP and mask
def network(ip,mask):

    network = ''

    iOctets = ip.split('.')
    mOctets = mask.split('.')

    network = str( int( iOctets[0] ) & int(mOctets[0] ) ) + '.'
    network += str( int( iOctets[1] ) & int(mOctets[1] ) ) + '.'
    network += str( int( iOctets[2] ) & int(mOctets[2] ) ) + '.'
    network += str( int( iOctets[3] ) & int(mOctets[3] ) )

    return network

您可以使用内置的 ipaddress 库:

import ipaddress
network = ipaddress.IPv4Network('10.0.0.20/255.255.255.0', strict=False)
print(network.network_address)

结果:

10.0.0.0