Monday, May 30, 2005

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

This snippet is an Oracle PL/SQL function that will convert an IP address from dotted-quad format (like 66.102.15.100) to the corresponding numeric value. This can be useful in a table where an IP address is entered by the end user in the familiar dotted quad format and a trigger is used to keep the numeric value of the IP address in synch. For the application, just use a regular expression to validate the IP address entered by the user.

FUNCTION dottedQuadToNumber (dottedQuad IN VARCHAR2)
RETURN NUMBER AS
BEGIN
  RETURN (
    (substr(dottedQuad,
            1,
            (instr(dottedQuad, '.', 1, 1) - 1))
            * 256 * 256 * 256
    ) +
    (substr(dottedQuad,
            instr(dottedQuad, '.', 1, 1) + 1,
            instr(dottedQuad, '.', 1, 2) -
            instr(dottedQuad, '.', 1, 1) - 1) * 256 * 256
    ) +
    (substr(dottedQuad,
            instr(dottedQuad, '.', 1, 2) + 1,
            instr(dottedQuad, '.', 1, 3) -
            instr(dottedQuad, '.', 1, 2) - 1) * 256
    ) +
    (substr(dottedQuad,
            instr(dottedQuad, '.', 1, 3) + 1)
    )
  );
END dottedQuadToNumber;

No comments: