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…

1.   <?php
3.   function ipaddress_to_ipnumber($ipaddress) {
4.   	$pton = @inet_pton($ipaddress);
5.   	if (!$pton) { return false; }
6.   	$number = '';
7.   	foreach (unpack('C*', $pton) as $byte) {
8.   		$number .= str_pad(decbin($byte), 8, '0', STR_PAD_LEFT);
9.   	}
10.  	return base_convert(ltrim($number, '0'), 2, 10);
11.  }
13.  ?>

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 (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:

1.   echo ipaddress_to_ipnumber('');
2.   //returns 1135714834
4.   echo ipaddress_to_ipnumber('');
5.   //returns 2488946353
7.   echo ipaddress_to_ipnumber('');
8.   //returns 2212761882
10.  echo ipaddress_to_ipnumber('FE80:0000:0000:0000:0202:B3FF:FE1E:8329');
11.  //returns 338288524927261046600406220626806860202
13.  echo ipaddress_to_ipnumber('2001:558:100A:4:68:87:68:162');
14.  //returns 42540596551066024442460608008464284482
16.  echo ipaddress_to_ipnumber('bogus');
17.  //returns 
19.  echo ipaddress_to_ipnumber('::1');
20.  //returns 1
22.  echo ipaddress_to_ipnumber('');
23.  //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.

1 Comment

January 24, 2016, 4:44 pm
thank you

Leave a Comment

Name and email are required. Your email will not be published.

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 & Conditions.