Python3 ip address to int algorithm

61.140.24.198BZ 1035664531
115.230.17.198BZ 1943074195
36.6.158.117P 607156768
117.67.49.165P 1970 0656752

this ip algorithm hasn"t been deduced for a long time, can you gods see it?

def ip2int (ip):

ip_list = ip.strip().split(".")
SUM = 0
for i in range(len(ip_list)):
    SUM += int(ip_list[i])*256**(3-i)
return SUM    

print (str (ip2int ("36.6.158.117") + str ("- > 36.6.158.117"))

print (str (ip2int ("115.230.17.198") + str ("- > 115.230.17.198")
604413557-> 36.6.158.117
1944457670-> 115.230.17.198
the answer is almost the same

.
Mar.17,2021


IPv4 wireshark IPv4 <strong>Source</strong> <strong>Destination</strong>

IPv4 4 <strong>big-endian</strong> <br> IP 0x01020304 01 02 03 04 "1.2.3.4"

SUM += int(ip_list[i])*256**(3-i)

can be understood as

SUM |= int(ip_list[i]) << (8*(3-i))

that is, the array elements are moved 24, 16, 8, 0 bits to the left, respectively.

in addition, there are more convenient methods, such as

import socket
import struct

-sharp  -> 
a = '1.2.3.4'
n = struct.unpack('>I', socket.inet_aton(a))[0]
assert n == 0x01020304

-sharp  -> 
a2 = socket.inet_ntoa(struct.pack('>I', n))
assert a2 == a
Menu