IP Address to IP Number (and back)

Version 2

    Description:

     

    IP Addresses typically appear as four numbers delimited by periods, i.e. 123.4.56.78. Sometimes, however, an equivalent form known as an IP number is used the IP Number is a single integer. This is common in lookup tables, since in most programming situations it is easier to do comparisons with a simple integer. Conceptually the conversion between these two is simple, since the IP address is actually just a 4 digit number in base 256 (with the digits separated by periods).

     

    Converting the IP address above to an IP number is 123*256^3+4*256^2+56*256+78 = 2063874126

    The main challenge in execution is parsing the individual digits from the IP address from string form, since each base 256 digit may be 1, 2 or 3 decimal digits.

     

    For completeness I also included the calculation in the other direction. The modulo operator % is the remainder term in integer division, it makes for a convenient way to change base.

     

     

    From IP Address to IP Number:


    //First compute the location of the delimiters, these are easiest to implement as 3 separate calculations.

    //Delimiter1

    find([IP Address],".")

    //Delimiter2

    find([IP Address],".",[Delimiter1]+1)

    //Delimiter2

    find([IP Address],".",[Delimiter2]+1)

    //Once the delimiter positions are known, they can be used to parse out individual base 256 digits.

    //IP Number

    int(left([IP Address],[Delimiter1]-1))*256^3+

    int(mid([IP Address],[Delimiter1]+1,[Delimiter2]-[Delimiter1]-1))*256^2+

    int(mid([IP Address],[Delimiter2]+1,[Delimiter3]-[Delimiter2]-1))*256+

    int(mid([IP Address],[Delimiter3]+1))

     

    From IP Number to IP Address:


    //Again, several calculations are used, first to create the individual digits, then to form the IP Address as a string

    //Digit1

    int([IP_Number]/256^3)%256

    //Digit2

    int([IP_Number]/256^2)%256

    //Digit3

    int([IP_Number]/256)%256

    //Digit4

    [IP_Number]%256

    //IP Address

    str([Digit1])+'.'+str([Digit2])+'.'+str([Digit3])+'.'+str([Digit4])



    Comments:


    Parsing strings like this can be tricky, having done this several times from scratch and there there always seems to be some wrinkle. I thought it might be nice to document. That way I'll know where to find it next time.

     

    I included a simple workbook that implements these calculations as an attachment.