Converting integer ip to ipaddress object. String ip is reversed?
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?
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.
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
精彩评论