Search code examples
pythonip-address

Python IP to integer conversion not working as expected


I am using the answer provided here to convert string IP to integer. But I am not getting expected output. Specifically, the method is

>>> ipstr = '1.2.3.4'
>>> parts = ipstr.split('.')
>>> (int(parts[0]) << 24) + (int(parts[1]) << 16) + \
          (int(parts[2]) << 8) + int(parts[3])

but when I provide it the value 172.31.22.98 I get 2887718498 back. However, I expect to see value -1407248798 as provided by Google's Guava library https://google.github.io/guava/releases/20.0/api/docs/com/google/common/net/InetAddresses.html#fromInteger-int-

Also, I've verified that this service provides expected output but all of the answers provided by the aforementioned StackOverflow answer return 2887718498

Note that I cannot use any third party library. So I am pretty much limited to using a hand-written code (no imports)


Solution

  • A better way is to use the library method

    >>> from socket import inet_aton
    >>> int.from_bytes(inet_aton('172.31.22.98'), byteorder="big")
    2887718498
    

    This is still the same result you had above

    Here is one way to view it as a signed int

    >>> from ctypes import c_long
    >>> c_long(2887718498)
    c_long(-1407248798)
    

    To do it without imports (but why? The above is all first party CPython)

    >>> x = 2887718498
    >>> if x >= (1<<31): x-= (1<<32)
    >>> x
    -1407248798