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

时间:2017-10-23 02:57:42

标签: python networking ip mask

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

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

3 个答案:

答案 0 :(得分:2)

模块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'

答案 1 :(得分:1)

好吧,我可能应该发布我所做的事情。它可以满足我的目的:

# 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

答案 2 :(得分:0)

您可以使用内置的ipaddress库:

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

结果:

10.0.0.0