How to unpack an IP packed in little endian byte order

Hello to forum members,

Here’s my issue : I have IPs stored in a database but those are “little
endian byte order” encoded and the field type of the BDD is BigInt
(similar to Ruby’s BigNum).

How could I get back my human readable IP ? I’ve been digging around
‘unpack’ for a while now but without success.

Here’s an example :
BigNum stored in the database : 3232235797
Resulting IP : 192.168.1.21

Could you give me some ideas or code ? I’m really stucked !

Thanks for all,

Liteo

2009/12/17 Nicolas V. [email protected]:

BigNum stored in the database : 3232235797
Resulting IP : 192.168.1.21

Could you give me some ideas or code ? I’m really stucked !

Do you mean like this:

irb(main):020:0> i
=> 3232235797
irb(main):021:0> ([i].pack(“N”)).unpack(“C*”)
=> [192, 168, 1, 21]
irb(main):022:0> ([i].pack(“N”)).unpack(“C*”).join(“.”)
=> “192.168.1.21”
irb(main):023:0>

Cheers

robert

Robert K. wrote:

2009/12/17 Nicolas V. [email protected]:

BigNum stored in the database : 3232235797
Resulting IP : 192.168.1.21

Could you give me some ideas or code ? I’m really stucked !

Do you mean like this:

irb(main):020:0> i
=> 3232235797
irb(main):021:0> ([i].pack(“N”)).unpack(“C*”)
=> [192, 168, 1, 21]
irb(main):022:0> ([i].pack(“N”)).unpack(“C*”).join(“.”)
=> “192.168.1.21”
irb(main):023:0>

Cheers

robert

That’s exactly it.

Thanks a lot Robert, you saved my day !

Hi,

Am Donnerstag, 17. Dez 2009, 22:57:30 +0900 schrieb Nicolas V.:

Here’s an example :
BigNum stored in the database : 3232235797
Resulting IP : 192.168.1.21

Here’s one without using pack/unpack:

ip = 3232235797
a = []
4.times { a.unshift ip & 0xff ; ip >>= 8 }
a.join “.”
#=> “192.168.1.21”

Bertram

Bertram S. wrote:

Hi,

Am Donnerstag, 17. Dez 2009, 22:57:30 +0900 schrieb Nicolas V.:

Here’s an example :
BigNum stored in the database : 3232235797
Resulting IP : 192.168.1.21

Here’s one without using pack/unpack:

ip = 3232235797
a = []
4.times { a.unshift ip & 0xff ; ip >>= 8 }
a.join “.”
#=> “192.168.1.21”

Bertram

Hi Bertram,

Thanks for your code explaining the underlying theory.

Regards,