How to unpack an IP packed in little endian byte order

N

Nicolas Vincent

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
 
R

Robert Klemme

2009/12/17 Nicolas Vincent said:
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 !

Do you mean like this:

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

Cheers

robert
 
N

Nicolas Vincent

Robert said:
2009/12/17 Nicolas Vincent said:
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> (.pack("N")).unpack("C*")
=> [192, 168, 1, 21]
irb(main):022:0> (.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 !
 
B

Bertram Scharpf

Hi,

Am Donnerstag, 17. Dez 2009, 22:57:30 +0900 schrieb Nicolas Vincent:
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
 
N

Nicolas Vincent

Bertram said:
Hi,

Am Donnerstag, 17. Dez 2009, 22:57:30 +0900 schrieb Nicolas Vincent:
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,
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,013
Latest member
KatriceSwa

Latest Threads

Top