Skip to content

Instantly share code, notes, and snippets.

@linhxhust
Created August 18, 2017 10:53
Show Gist options
  • Save linhxhust/cf33892740adb38d620a9c9c3bdeee34 to your computer and use it in GitHub Desktop.
Save linhxhust/cf33892740adb38d620a9c9c3bdeee34 to your computer and use it in GitHub Desktop.
Convert IP string to integer. Extract host_min, host_max from CIDR
import mysql.connector
import sys, struct, socket
def extract(cidr):
(ip, cidr) = cidr.split('/')
cidr = int(cidr)
host_bits = 32 - cidr
i = struct.unpack('>I', socket.inet_aton(ip))[0]
host_min = (i >> host_bits) << host_bits
host_max = i | ((1 << host_bits) - 1)
return (format_ip(host_min), format_ip(host_max))
def format_ip_string(i):
return socket.inet_ntoa(struct.pack('>I',i))
def string2int(s):
return reduce(lambda a,b: a<<8 | b, map(int, s.split(".")))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment