Page 1 of 1
Convert quad IP to hex
Posted: Tue Feb 05, 2008 11:02 am
by graceout777
I can't seem to find a php function to convert a dotted quad IP address to a hex value.
I was sure there should be one, but I've exhausted the php site.
Does anyone know of it, or (if there is none) does anyone know of a function that will perform this?
I know that MySql will do this upon input, but I need this done within the php script.
Thanks!!!
Jon
Re: Convert quad IP to hex
Posted: Tue Feb 05, 2008 11:15 am
by RobertGonzalez
Code: Select all
<?php
/**
* Converts a dotquad IP string into a hexidecimal IP string
* @access private
* @param string $user_ip Dot quad variant of the IP address
* @return string Hexadecimal encoding of the dot quad IP address
*/
function encode_ip($user_ip) {
// First thing to do, split the IP into its quads
$ip = explode('.', $user_ip);
// Now we convert it and return it to the caller
return sprintf('%02x%02x%02x%02x', $ip[0], $ip[1], $ip[2], $ip[3]);
}
/**
* Converts a hexidecimal IP string into a dotquad IP string
* @access private
* @param string $enc_ip The hexidecimal encoded IP address
* @return string The dot quad IP address
*/
function decode_ip($enc_ip) {
// First thing with this one is to take the 8 char hex IP and add a dot every two chars, the explode it
$ip_pop = explode('.', chunk_split($enc_ip, 2, '.'));
// Now send back a 'rebuilt' dotquad IP address
return hexdec($ip_pop[0]). '.' . hexdec($ip_pop[1]) . '.' . hexdec($ip_pop[2]) . '.' . hexdec($ip_pop[3]);
}
?>
I think I borrowed this from phpBB.
Re: Convert quad IP to hex
Posted: Tue Feb 05, 2008 11:21 am
by graceout777
Wow, that was fast!
I'll check it out and let you know how it works.
I thought I had dug through the phpBB code.
Appreciate it!
Jon
Re: Convert quad IP to hex
Posted: Tue Feb 05, 2008 11:23 am
by RobertGonzalez
phpBB used that in the 2.X release for tracking sessions. Look in the sessions.php in includes/ and you should run across something similar to it.
Re: Convert quad IP to hex
Posted: Tue Feb 05, 2008 12:42 pm
by graceout777
Thanks, Everah!
Works like a charm!!!
Jon Saboe
http://www.daysofpeleg.com
Re: Convert quad IP to hex
Posted: Tue Feb 05, 2008 2:38 pm
by RobertGonzalez
Glad I could help.