Created
August 18, 2017 10:53
-
-
Save linhxhust/cf33892740adb38d620a9c9c3bdeee34 to your computer and use it in GitHub Desktop.
Convert IP string to integer. Extract host_min, host_max from CIDR
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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