Convert IPv6 Address to IP Number with PHP

This PHP function will convert any IP address to its corresponding 32–bit decimal number! The exclamation mark is because I spent the better half of a day trying out various solutions before finally stumbling upon this one. With this function, you can convert both IPv4 addresses to IP numbers and IPv6 addresses to IP numbers. No need for two separate functions.

First, I'll share the function, and then the backstory…

<?php

function ipaddress_to_ipnumber($ipaddress) {
	$pton = @inet_pton($ipaddress);
	if (!$pton) { return false; }
	$number = '';
	foreach (unpack('C*', $pton) as $byte) {
		$number .= str_pad(decbin($byte), 8, '0', STR_PAD_LEFT);
	}
	return base_convert(ltrim($number, '0'), 2, 10);
}

?>

PHP has a built in function – ip2long – for converting IPv4 addresses, but it doesn't work on IPv6.

The FAQ that I was following on ip2location.com (where I purchased my IP address database from) had code to convert IPv6 to a number, but it included gmp_strval and I was running this particular project on a shared host where I couldn't easily install the GMP functions. After some searching, I pieced together a solution – the one that I've shared above – that didn't require GMP. Problem solved. (Or should we say avoided?)

Here are a few examples so you can see how easily it works:

echo ipaddress_to_ipnumber('67.177.162.18');
//returns 1135714834

echo ipaddress_to_ipnumber('148.90.78.177');
//returns 2488946353

echo ipaddress_to_ipnumber('131.228.17.26');
//returns 2212761882

echo ipaddress_to_ipnumber('FE80:0000:0000:0000:0202:B3FF:FE1E:8329');
//returns 338288524927261046600406220626806860202

echo ipaddress_to_ipnumber('2001:558:100A:4:68:87:68:162');
//returns 42540596551066024442460608008464284482

echo ipaddress_to_ipnumber('bogus');
//returns 

echo ipaddress_to_ipnumber('::1');
//returns 1

echo ipaddress_to_ipnumber('10.0.0.1');
//returns 167772161

Note that it just returned false when a bogus address was entered. And the last two examples are common local machine addresses.

If all you're wanting is to find your own IP number, visit our IP address lookup tool. It's listed right there, no code needed.


Comments

Loading…

This post was published on March 28th, 2015 by Robert James Reese in PHP. Before using any of the code or other content in this post, you must read and agree to our terms of use.