Zend - The PHP Company




Miscellaneous

Add Code


inet_ntop  

Type: code fragment
Added by: magicaltux
Entered: 27/05/2005
Last modified: 02/12/2005
Rating: - (fewer than 3 votes)
Views: 2330
Converts a binary IP to human-readable representation. This is a compatibility implementation of the original inet_ntop function at : http://www.php.net/inet_ntop


<?php

/* inet_ntop($data)
 * Converts a binary IP representation to a human-readable
 * string.
 * Code by M Karpeles ( http://www.nezumi.fr/ )
 */

function inet_ntop($ip) {
    if (
strlen($ip)==4) {
        
// IPv4
        
list(,$ip)=unpack('N',$ip);
        
$ip=long2ip($ip);
    } elseif(
strlen($ip)==16) {
        
// IPv6
        
$ip=bin2hex($ip);
        
$ip=substr(chunk_split($ip,4,':'),0,-1);
        
$ip=explode(':',$ip);
        
$res='';
        foreach(
$ip as $seg) {
            while(
$seg{0}=='0'$seg=substr($seg,1);
            if (
$seg!='') {
                
$res.=($res==''?'':':').$seg;
            } else {
                if (
strpos($res,'::')===false) {
                    if (
substr($res,-1)==':') continue;
                    
$res.=':';
                    continue;
                }
                
$res.=($res==''?'':':').'0';
            }
        }
        
$ip=$res;
    }
    return 
$ip;
}

?>


Usage Example


<?php
// Example from the PHP manual
$packed chr(127) . chr(0) . chr(0) . chr(1);
$expanded inet_ntop($packed);

/* Outputs: 127.0.0.1 */
echo $expanded;

$packed str_repeat(chr(0), 15) . chr(1);
$expanded inet_ntop($packed);

/* Outputs: ::1 */
echo $expanded;
?>


Rate This Script





Search



This Category All Categories