Skip to content

Instantly share code, notes, and snippets.

@keiya
Created June 10, 2013 23:22
Show Gist options
  • Select an option

  • Save keiya/5753330 to your computer and use it in GitHub Desktop.

Select an option

Save keiya/5753330 to your computer and use it in GitHub Desktop.
サブネット計算機
#!/usr/bin/python
# ip address util by Keiya Chinen
def binary_ip(dec_ip):
ip_l = dec_ip.split('.')
ip = (int(ip_l[0]) << 24) | (int(ip_l[1]) << 16) | (int(ip_l[2]) << 8) | int(ip_l[3])
return ip
def decimal_ip(bin_ip):
return (bin_ip >> 24, bin_ip >> 16 & 0xff, bin_ip >> 8 & 0xff, bin_ip & 0xff)
if __name__ == '__main__':
ip = '192.168.129.1'
mask = '255.255.255.0'
# test code
# print('{0[0]}.{0[1]}.{0[2]}.{0[3]}'.format(decimal_ip(binary_ip(ip))))
# calculates subnet address by [ip AND subnet-mask]
net = binary_ip(ip) & binary_ip(mask)
print('subnet numeric: {0}'.format(net))
# then, convert to human readable
net_h = decimal_ip(net)
print('subnet ip: {0[0]}.{0[1]}.{0[2]}.{0[3]}'.format(net_h))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment