Skip to content

Instantly share code, notes, and snippets.

@geek-at
Last active November 1, 2022 03:02
Show Gist options
  • Star 16 You must be signed in to star a gist
  • Fork 16 You must be signed in to fork a gist
  • Save geek-at/8473c8c0f28ca929e6f84e4e3d068241 to your computer and use it in GitHub Desktop.
Save geek-at/8473c8c0f28ca929e6f84e4e3d068241 to your computer and use it in GitHub Desktop.
Parsing ip data from a file
<?php
$infile = 'austria.csv';
$outfile = 'austria.ips';
$fp = fopen($outfile,'w');
$handle = fopen($infile, "r");
if ($handle)
{
while (($line = fgets($handle)) !== false) {
$line = trim($line);
$a = explode(',',$line);
$from = str_replace('"','',$a[0]);
$to = str_replace('"','',$a[1]);
for($i=$from;$i<=$to;$i++)
{
$ip = long2ip($i);
fwrite($fp,$ip."\n");
if(++$j % 10000==0)
echo ".";
}
}
fclose($handle);
}
fclose($fp);
@stefkes
Copy link

stefkes commented Dec 11, 2019

undefined variable $j

@geek-at
Copy link
Author

geek-at commented Dec 15, 2019

undefined variable $j

that's okay since $j is just used to output the dots

@spicystrips962
Copy link

while writing the python version of this script, I noticed the for loop goes only until $i<$to, and not $i<=$to, missing the last IP from every range.

@geek-at
Copy link
Author

geek-at commented Apr 5, 2020

Good catch, thanks

@ctrlsam
Copy link

ctrlsam commented Nov 1, 2022

For those who want a Python version:

import socket
import struct

input_file = open("austria.csv", "r")
output_file = open("austria.ips", "w")

for line in input_file:
  to_ip, from_ip, _, _ = line.replace("\"", "").split(",")

  to_ip = int(to_ip)
  from_ip = int(from_ip)

  for ip_index in range(to_ip, from_ip):
    ip = socket.inet_ntoa(struct.pack("!L", ip_index))
    output_file.write(ip + "\n")

input_file.close()
output_file.close()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment