简体   繁体   中英

Determine Network IP when given an IP and subnet mask

In Python, if I have an IP address and a subnet mask as string, how do I determine the network IP?

ie IP = 10.0.0.20, mask = 255.255.255.0 would result in a network IP of 10.0.0.0

The module ipcalc makes quick work of working with ip addresses as string:

Code:

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)

Results:

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

Well, I should probably post what I did.. It works for my purpose:

# 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

You can use the built-in ipaddress library:

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

Result:

10.0.0.0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM