Im Sprachumfang von PHP gibt es die Funktion long2ip schon lange. Sie konvertiert eine (IPv4) Netzwerkadresse in einen String, der das Punkt-Format enthält („Dotted-Format“). Z.B.
1440097712 -> 85.214.37.176 // www.k-oo.de
In Java habe ich sie gestern schmerzlich vermisst. Zum Glück gab es in der PHP Doku auch eine reine PHP Version des Konvertierungsalgorithmus (von Gabriel Malca). Die Übersetzung war dann einfach:
public static String long2Ip(long longValue) { StringBuffer ip = new StringBuffer(); if (longValue=0;i--) { ip.append((int)(longValue / Math.pow(256,i))); longValue -= (int)(longValue / Math.pow(256,i))*Math.pow(256,i); if (i>0) ip.append("."); } return ip.toString(); }
Diesen kleinen Code Schnipsel kann wie immer jeder ohne Gewähr nutzen.
public static long ipToInt_2(String addr) {
String[] addressBytes = addr.split(„\.“);
int ip = 0;
for (int i = 0; i < 4; i++) {
ip <<= 8;
ip |= Integer.parseInt(addressBytes[i]);
}
return ip;
}
public static String intToIp(long i) {
return ((i >> 24) & 0xFF) + „.“ +
((i >> 16) & 0xFF) + „.“ +
((i >> 8) & 0xFF) + „.“ +
(i & 0xFF);
}
Wow, the last one works and i needed a little bit to figure it out why 🙂
The Bitwise Operator & was the knot i need to look at. Thanks for the cool one-liner, even in Perl i can use it 😀
sub __calcIP {
my $long = shift;
return (($long >> 24) & 0xFF) . ‚.‘ . (($long >> 16) & 0xFF) . ‚.‘ . (($long >> 8) & 0xFF) . ‚.‘ . ($long & 0xFF);
}
So long
Lord Pinhead