-1

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)

user375868
  • 1,288
  • 4
  • 21
  • 45
  • 1
    2887718498 and -1407248798 represent the same number... One is a signed, and the other an unsigned 32 bit integer, with the same value. – Stephen Rauch Feb 13 '18 at 04:17
  • @StephenRauch It's the same bit pattern. But the numbers are visibly very different, due to the different interpretations of the pattern. – DYZ Feb 13 '18 at 04:19
  • @DyZ, what? Are you saying my analysis of the situation is incorrect, or just that my choice of language is not precise enough? – Stephen Rauch Feb 13 '18 at 04:21
  • You choice of language. – DYZ Feb 13 '18 at 04:27

2 Answers2

1

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
John La Rooy
  • 295,403
  • 53
  • 369
  • 502
0

Found this post whilst trying to do the same as OP. Developed the below for my simple mind to understand and for someone to benefit from.

baseIP = '192.168.1.0'
baseIPFirstOctet = (int((baseIP).split('.')[0]))
baseIPSecondOctet = (int((baseIP).split('.')[1]))
baseIPThirdOctet = (int((baseIP).split('.')[2]))
baseIPFourthOctet = (int((baseIP).split('.')[3]))