Created
November 26, 2010 13:40
-
-
Save jaymzcd/716719 to your computer and use it in GitHub Desktop.
Takes a list of CIDR formatted IP's and outputs the network & broadcast address in decimal format - handy to do arithmetic based queries in a database.
This file contains hidden or 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
| #!/usr/bin/env python2 | |
| import sys | |
| import csv | |
| import ipaddr # via code.google.com/p/ipaddr-py/ | |
| # Reads a file of ip's and spits out decimal start/end points | |
| # http://ipinfodb.com/ip_database.php | |
| # Then load into mysql and select the country you fancy into a file: | |
| # SELECT ip_cidr, country_code FROM ip_group_country WHERE country_code IN ("IT", "DE") INTO OUTFILE '/tmp/eu-ips.txt'; | |
| # The output can go into a table like this: | |
| # | |
| # CREATE TABLE iplookup ( | |
| # id MEDIUMINT NOT NULL AUTO_INCREMENT, | |
| # network_address VARCHAR(15) NOT NULL, | |
| # broadcast_address VARCHAR(15) NOT NULL, | |
| # network_decimal INTEGER NOT NULL, | |
| # broadcast_decimal INTEGER NOT NULL, | |
| # country_code VARCHAR(2) NOT NULL, | |
| # PRIMARY KEY(id) | |
| # ) ENGINE MyISAM; | |
| # | |
| # Then you need to load it in via your output csv: | |
| # | |
| # LOAD DATA INFILE '/tmp/out.csv' INTO TABLE iplookup FIELDS TERMINATED BY ',' | |
| # ENCLOSED BY '"' LINES TERMINATED BY '\r\n' | |
| # (network_address, broadcast_address, network_decimal, broadcast_decimal, country_code); | |
| # | |
| # Now query! | |
| MULTS = [256**3, 256**2, 256, 1] # For decimal conversion - each chunk of the ip4 addy | |
| def to_decimal(addr): | |
| """ Converts an input (string) ipv address to decimal equivilant for | |
| easier arthemtic in the database """ | |
| decimal_ip = 0 | |
| parts = enumerate(str(addr).split('.')) | |
| for (index, part) in parts: | |
| decimal_ip += int(part)*MULTS[index] | |
| return decimal_ip | |
| def processInput(): | |
| """ Read in and process our list of ips """ | |
| input_file = open(sys.argv[1]) | |
| output_file = csv.writer(open(sys.argv[2], 'w+'), quotechar='"', \ | |
| quoting=csv.QUOTE_ALL) | |
| for line in input_file: | |
| line = line.split('\t') | |
| network = ipaddr.IPNetwork(line[0]) | |
| c_code = line[1].strip() | |
| network_iter = network.iterhosts() | |
| output_file.writerow([str(network.network), str(network.broadcast), \ | |
| to_decimal(network.network), to_decimal(network.broadcast), c_code]) | |
| if __name__ == '__main__': | |
| processInput() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment