dapperwaterbuffalo
dapperwaterbuffalo

Reputation: 2748

Restricting access via IP-ranges (PHP)

Basically, I aim to allow my user to specify an ip range for access to a test. So lets say these values are stored in my database:

from: 148.197.34.112

To: 148.197.34.255

Are there any functions of which I can use to convert these ip addresses into numbers for comparison?

So obviously if a user tries to load a page...if his IP is not within an ip range, re-direct them.

Thanks in advance :)

Upvotes: 4

Views: 755

Answers (2)

Paolo Stefan
Paolo Stefan

Reputation: 10253

The ip2long() function will do the job for a IPv4 address.

To convert an IPv6 address to a 128-bit integer, use the inet_pton() function.

Upvotes: 6

user680786
user680786

Reputation:

If values stored in database exactly in this format, then you can use INET_ATON function (for mysql, at least) and ip2long() in php.

$iplong=ip2long($ip);
$q=mysql_query("SELECT * FROM ips WHERE INET_ATON(ip_from)<='".$iplong."' AND INET_ATON(ip_to)>='".$iplong."' LIMIT 0,1");

But, of course, it will be much better to store long values in DB, instead of pure IP.

Upvotes: 1

Related Questions