Answer the question
In order to leave comments, you need to log in
Implementation of long2ip(). How to convert ip from long to string?
from a string to a number I convert according to the formula
1октет * pow(256, 3) + 2октет * pow(256, 2) + 3октет * pow(256, 1) + 4октет * pow(256, 0)
77.88.21.8
77 * pow(256, 3) + 88 * pow(256, 2) + 21 * pow(256, 1) + 8 * pow(256, 0) = 1297618184.
1297618184 => 77.88.21.8
Answer the question
In order to leave comments, you need to log in
On a sishka, an example code would be like this
long int x=1297618184;
int oct[4];
for(int i=3;i>=0;i--){
oct[3-i] = x/pow(256,3);
x = x%pow(256,3);
}
printf("%d.%d.%d.%d",oct[0],oct[1],oct[2],oct[3]);
If you want to reinvent the wheel, use the struct module to pack a 32-bit value into a string and unpack the result as 4 bytes.
If you want to solve the problem without too much effort, you can use the netaddr module :
>>> import netaddr
>>> int(netaddr.IPAddress('77.88.21.8'))
1297618184
>>> str(netaddr.IPAddress(1297618184))
'77.88.21.8'
I had the task of doing these transformations myself,Keep then two fancy one-liners:
def long_to_dotted_decimal(val):
return '.'.join(map(str,[val%256**idx/256**(idx-1) for idx in xrange(4,0,-1)]))
def dotted_decimal_to_long(strval):
return sum(map(lambda (power,octet):256**power*int(octet),enumerate(reversed(strval.split('.')))))
>>> long_to_dotted_decimal(dotted_decimal_to_long('127.0.0.1'))
'127.0.0.1'
>>> long_to_dotted_decimal(dotted_decimal_to_long('255.255.255.255'))
'255.255.255.255'
>>> long_to_dotted_decimal(1297618184)
'77.88.21.8'
>>> dotted_decimal_to_long('77.88.21.8')
1297618184
1297618184/ pow(256, 3) + . + 1297618184 * pow(256, 2) + . + 1297618184/ pow(256, 1) + . + 1297618184/ pow(256, 0)
You need to get octets from a 4-byte number, convert the octets to a string representation in decimal, and connect the strings with dots.
function ip2long($ipstr)
{
$ip = explode('.', $ipstr);
$ipl32 = ($ip[0] << 24) + ($ip[1] << 16) + ($ip[2] << 8) + $ip[3];
return $ipl32;
}
function long2ip($ipl32)
{
$ip[0] = ($ipl32 >> 24) & 255;
$ip[1] = ($ipl32 >> 16) & 255;
$ip[2] = ($ipl32 >> 8) & 255;
$ip[3] = $ipl32 & 255;
$ipstr = implode('.', $ip);
return $ipstr;
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question