1

I'm deserializing data from a web page generated by php that is using ip2long(). However, when I try to make a new ip address by using the integer value in the constructor of IPAddress the dotted version of the ip address is in reverse order?

ex:

4.3.2.1 should really be 1.2.3.4

Any ideas of how to fix this?

Suman Banerjee
  • 1,923
  • 4
  • 24
  • 40
Josh
  • 2,083
  • 5
  • 23
  • 28

2 Answers2

1

It sounds like someone is using little-endian and someone is using network byte order (big-endian) for the packed value. For instance the octect sequence compromising an integer, AA,BB,CC,DD in LE is DD,CC,BB,AA in BE/NBO -- a nice symmetrical reverse!

Since the IPAddress(Int64) constructor documentations says:

The Int64 value is assumed to be in network byte order.

I would imagine that ip2long in PHP is generating a value in little-endian. Good thing IPAddress also takes byte[] for the constructor, now get those elbows greasy... just pass the bytes in the "correct" order.

Happy coding.


The code at How to convert an int to a little endian byte array? should give some ideas.


Or, as Josh points out, there is a HostToNetworkOrder method to do this.

Community
  • 1
  • 1
  • Thanks. I found that IPAddress actually has a method for converting from host to network byte order. – Josh Sep 09 '11 at 03:54
0

use long2ip() to reverse the process of ip2long()

<?php
// make sure IPs are valid. also converts a non-complete IP into
// a proper dotted quad as explained below.
$ip = long2ip(ip2long("127.0.0.1")); // "127.0.0.1"
$ip = long2ip(ip2long("10.0.0")); // "10.0.0.0"
$ip = long2ip(ip2long("10.0.256")); // "10.0.1.0"
?>

you shouldn't really have any problems after all it's a standard in php

SSpoke
  • 5,656
  • 10
  • 72
  • 124
  • Yes. While not explicit it sounds like the decoding is done in C# ... somewhere ... for some reason. –  Sep 09 '11 at 03:41
  • I don't have any control over the output of the php page. They are giving the integer value from ip2long() for me to use. – Josh Sep 09 '11 at 03:41