Converting IP Addresses With ip2long...

Hello,

I’m new here so please no flaming. I have been writing a little piece of code to convert a range of IP addresses into long format. However, for the life of me I cannot figure out why this is not working. It only echos the start IP address and not the end IP address.

The test file contains the following line:
1.52.0.0 - 1.52.10.15

This is just a sample IP range, nothing special. My code is as follows:
[php]<?php

$long_ip = ip2long($_SERVER[‘REMOTE_ADDR’]); // Retrieve remote IP and convert to long.

$filepointer = fopen(“vn_ip_ranges.txt”,“r”); // Open the file as read only.
$line = fgets($filepointer, 128); // Get the first line of data out of file.
$trimmed_line = str_replace(" “,”",$line); // Remove all spaces from line of data.
$ip_range = explode("-", $trimmed_line); // Split the line of data in an array.

$start_ip = ip2long($ip_range[0]); // Convert start IP to long.
$end_ip = ip2long($ip_range[1]); // Convert end IP to long.

echo “Start “.$start_ip.”
”; // Echo long start IP.
echo “End “.$end_ip.”
”; // Echo long end IP.

fclose($filepointer); // Close file.

?>
[/php]

Can anybody help me?

Thank you.

It seems I figured it out. For some reason after exploding $trimmed_line there is still a whitespace at the end of the value that causes ip2long to fail.

Ok, now that I have that fixed, why are the values returned by ip2long sometimes negative? I read this information about integer types being signed, but I don’t fully understand.

Although I had nobody’s help here I did figure it out. I wrote the PHP code to look at a text file containing many IP address ranges, and if the client’s IP address is found to default my website to Vietnamese.

I’ve found several other people inquiring about similar things, but it wasn’t the same as I needed. That and the code other people used is totally different than mine. I’m sure mine can be done better, but it works.

If anybody’s interested I can post it here or send it.

Sponsor our Newsletter | Privacy Policy | Terms of Service