long2ip – IP Adressen Konvertierung für Java

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.

3 Kommentare

  1. Try This · · Antworten

    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;
    }

  2. and this · · Antworten

    public static String intToIp(long i) {
    return ((i >> 24) & 0xFF) + „.“ +
    ((i >> 16) & 0xFF) + „.“ +
    ((i >> 8) & 0xFF) + „.“ +
    (i & 0xFF);
    }

  3. 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

Kommentar verfassen

Trage deine Daten unten ein oder klicke ein Icon um dich einzuloggen:

WordPress.com-Logo

Du kommentierst mit Deinem WordPress.com-Konto. Abmelden /  Ändern )

Twitter-Bild

Du kommentierst mit Deinem Twitter-Konto. Abmelden /  Ändern )

Facebook-Foto

Du kommentierst mit Deinem Facebook-Konto. Abmelden /  Ändern )

Verbinde mit %s

%d Bloggern gefällt das: