L
L
LittleFatNinja2015-06-13 12:44:55
PHP
LittleFatNinja, 2015-06-13 12:44:55

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.

but vice versa, I can’t, there are problems with the matan,
1297618184 => 77.88.21.8
if you can just tell me, I already write the code myself

Answer the question

In order to leave comments, you need to log in

5 answer(s)
M
Michael, 2015-06-13
@LittleFatNinja

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]);

ps / is an integer division, and % is the remainder of the division

T
throughtheether, 2015-06-13
@throughtheether

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'

UPD :
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('.')))))

Usage example:
>>> 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

S
sivabur, 2015-06-13
@sivabur

1297618184/ pow(256, 3) + . + 1297618184 * pow(256, 2) + . + 1297618184/ pow(256, 1) + . + 1297618184/ pow(256, 0)

R
Roman Mirilaczvili, 2015-06-13
@2ord

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.

H
HarpyWar, 2015-07-02
@HarpyWar

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;
}

PHP already has these functions. For Python too:
www.php2python.com/wiki/function.ip2long
www.php2python.com/wiki/function.long2ip

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question