Convert quad IP to hex

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
graceout777
Forum Newbie
Posts: 3
Joined: Tue Feb 05, 2008 10:54 am

Convert quad IP to hex

Post 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
User avatar
RobertGonzalez
Site Administrator
Posts: 14293
Joined: Tue Sep 09, 2003 6:04 pm
Location: Fremont, CA, USA

Re: Convert quad IP to hex

Post 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.
graceout777
Forum Newbie
Posts: 3
Joined: Tue Feb 05, 2008 10:54 am

Re: Convert quad IP to hex

Post 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
User avatar
RobertGonzalez
Site Administrator
Posts: 14293
Joined: Tue Sep 09, 2003 6:04 pm
Location: Fremont, CA, USA

Re: Convert quad IP to hex

Post 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.
graceout777
Forum Newbie
Posts: 3
Joined: Tue Feb 05, 2008 10:54 am

Re: Convert quad IP to hex

Post by graceout777 »

Thanks, Everah!

Works like a charm!!!

Jon Saboe

http://www.daysofpeleg.com
User avatar
RobertGonzalez
Site Administrator
Posts: 14293
Joined: Tue Sep 09, 2003 6:04 pm
Location: Fremont, CA, USA

Re: Convert quad IP to hex

Post by RobertGonzalez »

Glad I could help.
Post Reply