Premium Member Database last update: Friday, September 30, 2016 6:02:48 GMT-0700

Remove leading zeros from IP Address octets

There may be times you encounter IP addresses with leading zeros in the octets. Using IP addresses with leading zeros can cause some undesired behavior in your scripts. Recently someone approached us about resolving such a problem with a list found at http://isc.sans.edu/ipsascii.html?limit=10000. Having a rare few minutes of time available I wrote a quick script to resolve this problem. While this script does remove leading zeros it may need to be modified to work with your list.

Here is the script:

$filename="http://isc.sans.edu/ipsascii.html?limit=10000";
$fh = fopen($filename, "r");
	
			while(!feof($fh)) {
			
			$content=fgetss($fh);

			$ip_address = strtok($content, " ");
			if($ip_address !== '#')	{
			$ip1 = strtok($ip_address, ".");
			$ip2 = strtok(".");
			$ip3 =  strtok(".");
			$ip_reduce = strtok(" ");
			

			$ip4 = substr($ip_reduce, 0, 3); 
			


		$ip1 = preg_replace('/^0+(.)/', "$1", $ip1);
		$ip2 = preg_replace('/^0+(.)/', "$1", $ip2);
		$ip3 = preg_replace('/^0+(.)/', "$1", $ip3);
		$ip4 = preg_replace('/^0+(.)/', "$1", $ip4);

	$ip_address = $ip1 . "." .  $ip2 . "." .  $ip3 . "." .  $ip4;
	
	echo $ip_address . "
"; } } fclose($fh)

You may freely reuse this script if you give attribution to Country IP Blocks and provide a link to our homepage.