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

···

--
Posted via http://www.ruby-forum.com/.

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

···

2009/12/17 Nicolas Vincent <n.galineau@gmail.com>:

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 !

--
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/

Hi,

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

···

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

--
Bertram Scharpf
Stuttgart, Deutschland/Germany
*
Discover String#notempty? at <http://raa.ruby-lang.org/project/step&gt;\.

Robert Klemme wrote:

···

2009/12/17 Nicolas Vincent <n.galineau@gmail.com>:

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 !
--
Posted via http://www.ruby-forum.com/\.

Bertram Scharpf wrote:

Hi,

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,

···

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

--
Posted via http://www.ruby-forum.com/\.