星期三, 6月 26, 2013

用IP和netmask計算subnet

因為現有的Python package都太大包了,我只需要計算subnet而已,所以,找到一篇[1]看起來最簡單的,程式如下︰
#!/usr/bin/env python

def calc_subnet(ip, netmask):
  a = [int(n) for n in ip.split('.')]
  b = [int(n) for n in netmask.split('.')]
  c = zip(a,b)
  return '.'.join([str(a & m) for a, m in c])

ip = '192.168.1.2'
netmask = '255.255.0.0'
print calc_subnet(ip, netmask)

[1] Amusement: Python and Netmasks, http://unroutable.blogspot.tw/2012/01/amusement-python-and-netmasks.html