Calab
Calab

Reputation: 363

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?

i.e. IP = 10.0.0.20, mask = 255.255.255.0 would result in a network IP of 10.0.0.0

Upvotes: 3

Views: 11742

Answers (4)

somesh kovi
somesh kovi

Reputation: 24

import ipaddress
network_address = ipaddress.ip_network('1000::5665/96', strict=False).network_address
#works for both ipv4 and ipv6
print(network_address)

Upvotes: 0

jojo
jojo

Reputation: 121

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

Upvotes: 12

Calab
Calab

Reputation: 363

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

Upvotes: 2

Stephen Rauch
Stephen Rauch

Reputation: 49774

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'

Upvotes: 4

Related Questions