Monday, May 30, 2005

Oracle PL/SQL function to convert numeric IP address to dotted-quad

This snippet is an Oracle PL/SQL function that will convert an IP address from numeric format to the corresponding dotted-quad string.

FUNCTION numberToDottedQuad(dottedQuad IN NUMBER)
RETURN VARCHAR2 AS
    item NUMBER;
    part1 VARCHAR2(3);
    part2 VARCHAR2(3);
    part3 VARCHAR2(3);
    part4 VARCHAR2(3);
    divisor NUMBER;
BEGIN
    item := dottedQuad;

    divisor := 256*256*256;
    part1 := TRUNC(item / divisor);
    item := MOD(item, divisor);

    divisor := 256*256;
    part2 := TRUNC(item / divisor);
    item := MOD(item, divisor);

    divisor := 256;
    part3 := TRUNC(item / divisor);
    item := MOD(item, divisor);

    part4 := item;

    -- piece them together for the result
    RETURN part1 || '.' || part2 || '.' || part3 || '.' || part4;
END numberToDottedQuad;

No comments: