The easiest way to do this in my experience is to use two third-party packages:
So, install these modules, and then it will be so simple:
import netifaces
import netaddr
import socket
from pprint import pformat
ifaces = netifaces.interfaces()
myiface = 'eth0'
addrs = netifaces.ifaddresses(myiface)
ipinfo = addrs[socket.AF_INET][0]
address = ipinfo['addr']
netmask = ipinfo['netmask']
cidr = netaddr.IPNetwork('%s/%s' % (address, netmask))
network = cidr.network
print 'Network info for %s:' % myiface
print '--'
print 'address:', address
print 'netmask:', netmask
print ' cidr:', cidr
print 'network:', network
And it gives out:
Network info for eth0:
--
address: 192.168.1.150
netmask: 255.255.255.0
cidr: 192.168.1.150/24
network: 192.168.1.0
Linux. OSX , .